I am attempting to dynamically add a CSS class to a component right after its creation by utilizing ViewContainerRef
and ComponentFactoryResolver
. My goal is to determine the class based on which other Components have already been added to 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)
// Successfully adding SomeBaseComponent to myContainerRef
// Trying to add CSS class to the newly created component
// The following statements do not apply 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) {}
}
Is there a more effective approach to programmatically adding styles? Is there something else I can inject into SomeBaseComponent
to enable setting the desired styles at this stage, or should I use flags on newComponent.instance
and let the base component manage its own style settings?