Is it possible to add a dynamic class to host in Angular 2?

Alec Sibilia picture Alec Sibilia · Mar 14, 2016 · Viewed 22.3k times · Source

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

Answer

Günter Zöchbauer picture Günter Zöchbauer · Apr 14, 2016

The Renderers setElementClass can be used to add or remove an arbitrary class. For example md-[color] where color is provided by an input

<some-cmp [color]="red">
@Component({
// @Directive({
    selector: 'some-cmp',
    template: '...'
})
export class SomeComp {
    _color: string;

    @Input()
    set color(color: string) {
        this._color = color;
        this.renderer.setElementClass(this.elementRef.nativeElement, 'md-' + this._color, true);
    }

    get color(): string {
        return this._color;
    }

    constructor(private elementRef: ElementRef, private renderer: Renderer){}
} 

See also nativeElement.classList.add() alternative