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

Problem

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';
}
Problem courtesy of: Alec Sibilia

Solution

You can use something like that:

@Directive({
  (...)
  host: {
    '[class.className]' : 'className', 
    '[class]' : 'classNames' 
  }
}
export class MyDirective {
  constructor() {
    this.className = true;
    this.classNames = 'class1 class2 class3';
  }
}
Solution courtesy of: Thierry Templier

Discussion

import {Component, HostBinding} from 'angular2/core';

@Component({
  (...)
}

export class MyComponent {
  @HostBinding('class') colorClass = 'red';
}
Discussion courtesy of: fransoudelaar

If you like to change it from outside you can combine @HostBinding and @Input():

@Component({
    selector: 'my-component',
    template: ``
})
export class MyComponent {
    @HostBinding('class.your-class') @Input() isSelected: boolean;
}
Discussion courtesy of: crashbus

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() {
        this.renderer.setElementClass(this.elementRef.nativeElement, 'md-' + this.color_, true);
    }

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

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

See also looking for nativeElement.classList.add() alternative

Discussion courtesy of: Günter Zöchbauer

You can do the following:

import {Component} from "@angular/core"

@Component({
    selector: "[textbox]",
    host: {"class": "first-class secondClass ThirdClass AnYClaSs"},
    template: ...                                            
})
export class MyComponent { }

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.

Discussion courtesy of: Yaroslav Yakovlev

This recipe can be found in it's original form on Stack Over Flow.