Home > Mobile >  ngclass not working with dynamically created components
ngclass not working with dynamically created components

Time:11-10

I have some components that I create using createComponent. While some components work correctly some don't have proper css classes. I'm using a function and [ngClass] to set the classes but they just aren't there when I inspect the component in dom.

constructor (private injector: EnvironmentInjector) {};
const compRef = createComponent(RadioButtonComponent, { environmentInjector: this.injector});
document.body.appendChild(compRef.location.nativeElement);

Radio button has code radio.component.html

<div [ngClass]="classes">
...
</div>

radio.component.ts

public get classes(): string[] {
let cls: string[] = [];
cls.push('some-class-name');
return cls;
}

CodePudding user response:

I think your classes are nor rendered because, you inject your component in the dom but not in the Angular dom. So, I think Angular do not know about your created component and does not trigger get classes().

Instead of using document.body.appendChild, use [Renderer2][1] and call his appendChild method.

constructor(
    private renderer2: Renderer2,
    private injector: EnvironmentInjector
    ) {}
...
const compRef = createComponent(RadioButtonComponent, { environmentInjector: this.injector});
this.renderer2.appendChild(THE_PARENT_ELEMENT, compRef.location.nativeElement);

THE_PARENT_ELEMENT is like elementRef.nativeElement.

CodePudding user response:

In order for angular to run change detection on your created component you have to attach it to the application as explained here in the docs.

In your case you could probably inject the ApplicationRef in your constructor and use it like this:

    constructor (private injector: EnvironmentInjector, private applicationRef: ApplicationRef) {};
    
    const compRef = createComponent(RadioButtonComponent, { environmentInjector: this.injector});
    applicationRef.attachView(compRef.hostView); // this line was added

    document.body.appendChild(compRef.location.nativeElement);
  • Related