I have dynamically created element
initElem() {
let childElFactory = this._cfRes.resolveComponentFactory(childElCmp);
// _cfRes is ComponentFactoryResolver
let childElRef = this._vcRef.createComponent(childElFactory);
// _vcRef is ViewContainerRef
childElRef.instance.childElModel = someModel;
}
and I want to add
[ngClass]="{active: childElModel.active}"
attribiute and
#childEl
attribiute to host element of childElCmp.
I don't want to use elementRef as it's not a proper way. I think Renderer is what I am looking for but I don't know how to use it in the right way.
You can simply add @HostBinding('class') class = 'someClass'; inside your @Component class. The className directive may also be used and it is better to avoid using class as a variable name (since you might reference it and change it later). Example: @HostBinding('className') myTheme = 'theme-dark'; .
You can't apply [ngClass]...
or any other binding to a dynamically added component.
You can add
@HostBinding('class.active') isActive:boolean = false;
into your dynamically added component and then use
childref.instance.isActive = true;
To get the active
class added/removed from the component.
Or you can inject ElementRef
into the parent component and use
elementRef.nativeElement.querySelector('child-el').classList.add('active');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With