我尝试在使用ViewContainerRef
和ComponentFactoryResolver
创建组件后立即向它添加一个CSS类。我希望能够根据已经添加到myViewContainerRef
的其他组件来设置类。
export class ContainerComponent {
@ViewChild('myContainerRef') myContainerRef: ViewContainerRef
constructor(private factoryResolver: ComponentFactoryResolver,
private renderer: Renderer2) {}
addComponent() {
const componentFactory = this.factoryResolver.resolveComponentFactory(SomeBaseComponent)
const newComponent = this.myContainerRef.createComponent(componentFactory)
// SomeBaseComponent has been added successfully to myContainerRef
// Want to add CSS class to the newComponent
// None of the following statements are adding any styles
if( someLogic()) {
this.renderer.addClass(newComponent.location.nativeElement, 'my-css-class')
this.renderer.addClass(newComponent.el.nativeElement, 'my-css-class')
this.renderer.setStyle(newComponent.el.nativeElement, 'background', 'yellow')
}
}
}
export class SomeBaseComponent {
constructor(public el: ElementRef) {}
}
有没有更好的方式尝试以编程方式添加样式?还有没有其他东西可以注入到SomeBaseComponent
中,以便能够在这一点上添加我想要的样式,或者我应该在newComponent.instance
上设置标志,并让基本组件控制自己设置什么样式?
发布于 2018-07-28 06:28:13
您应该添加另一个@ViewChild,它将具有ElementRef
类型的read。
@ViewChild("myContainerRef", {read: ElementRef}) elementRef: ElementRef;
要设置类的属性,您应该使用以下方法。
this.elementRef.nativeElement.setAttribute("class", "test")
注意:我建议将创建逻辑放在ngOnInit()
方法中,放在自定义addComponent()
中。
https://stackoverflow.com/questions/51566181
复制相似问题