Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to add [ngClass] to host element programmatically if element was created dynamically?

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.

like image 978
Sakala Avatar asked Oct 18 '16 08:10

Sakala


People also ask

How do I add a class to my host?

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'; .


1 Answers

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');
like image 150
Günter Zöchbauer Avatar answered Nov 15 '22 08:11

Günter Zöchbauer