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

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


You can use something like that:

@Directive({
  (...)
  host: {
    '[class.className]' : 'className', 
    '[class]' : 'classNames' 
  }
}
export class MyDirective {
  className: boolean;
  classNames: string;

  constructor() {
    this.className = true;
    this.classNames = 'class1 class2 class3';
  }
}