Kaleem Nalband
Kaleem Nalband

Reputation: 697

Adding class to dynamically created component angular

i have the following code,

createComponent(message, some_css_class) {
    this.msg.reset();
    const factory = this.resolver.resolveComponentFactory(MessageComponent);
    const componentRef = this.entry.createComponent(factory);
    componentRef.instance.message = message;
    //how to add the passed css class to the this component
}

here i dynamically create the component, now need to add the passed css class to it.

Upvotes: 1

Views: 1215

Answers (2)

Sasi Kumar M
Sasi Kumar M

Reputation: 2630

In Angular 5/6, using Renderer2 from @angular/core, you can try like below,

constructor(private resolver: ComponentFactoryResolver, private renderer2: Renderer2) { }

createComponent(message, some_css_class) {
    this.msg.reset();
    const factory = this.resolver.resolveComponentFactory(MessageComponent);
    const componentRef = this.entry.createComponent(factory);
    componentRef.instance.message = message;
    this.renderer2.addClass(componentRef.location.nativeElement, some_css_class);
}

Upvotes: 1

Andrei
Andrei

Reputation: 12151

you could use componentRef.instance.cssClass = some_css_class and @HostBinding('class') public cssClass; inside of a component

Upvotes: 0

Related Questions