I know that in Angular2 I can add a class 'red' to a component's selector element by doing this:
@Component({
selector: 'selector-el',
host: {
'[class.red]': 'true'
},
...
})
I'm wondering whether there's a way to add a dynamic class to a host, similar to what you would do with NgClass (I know NgClass is not actually supported, I'm looking for possible solutions):
@Component({
selector: 'selector-el',
host: {
'[NgClass]': 'colorClass'
},
...
})
...
constructor(){
this.colorClass = 'red';
}
The
Renderer
ssetElementClass
can be used to add or remove an arbitrary class. For examplemd-[color]
wherecolor
is provided by an inputSee also looking for nativeElement.classList.add() alternative
I have recently made a directive called
<ng-host>
(inspired by this issue), it will redirect every (non-structural) change to the component host element, usage:Online demo can be found here.
Supported usages defined here.
I have achieved this by the Directive as a Service pattern, namely manually providingNgClass
and use it like (online demo)Due to the DI mechanism,NgClass
will get theElementRef
of current host element, theSelf()
modifier helps to guarantee it. So no need to create an instance by constructor, thus still under public API usage.It could be more concise when combined with class inheritance, an example can be found at here.You can use something like that:
You can do the following:
Which is imo way more straightforward than introducing a variable.
Should work in Angular2 rc5, rc6, rc7, final. May work in earlier versions, but didnt try it.
If you like to change it from outside you can combine
@HostBinding
and@Input()
: