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

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


Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

I did it in this way. Maybe someone will come in handy

@HostBinding('class') get hostClasses() {
    return `some-class ${this.dynamicOne} ${this.disabled ? 'disabled' : ''}`;
}

OR Simon_Weaver's Suggestion: (the return value can also be an array, Thank you!)

@HostBinding('class') get hostClasses() {
  const classList = ['some-class', this.dynamicOne];
  if( this.disabled) { classList.push('disabled'); }
  return classList;
}

Solution 4:[4]

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

@Component({
  (...)
}

export class MyComponent {
  @HostBinding('class') colorClass = 'red';
}

Solution 5:[5]

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:

@Component({
  template: `
    <ng-host [ngClass]="{foo: true, bar: false}"></ng-host>
    <p>Hello World!</p>
  `
})
class AppComponent { }

Online demo can be found here.

Supported usages defined here.

I have achieved this by the Directive as a Service pattern, namely manually providing NgClass and use it like (online demo)

Due to the DI mechanism, NgClass will get the ElementRef of current host element, the Self() 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.

Solution 6:[6]

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.

Solution 7:[7]

This is what worked for me:

import { Component, Attribute, HostBinding } from "@angular/core";

@Component({
    selector: "selector-el",
    template: ...                                            
})
export class MyComponent {
    @HostBinding('class') get classAttribute(): string {
        let defaultClasses = 'selector-el-class';
        return defaultClasses + ' ' + this.classNames;
    }

    constructor(
        @Attribute('class') public classNames: string
    ) { }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FabiF
Solution 2 crashbus
Solution 3
Solution 4 fransoudelaar
Solution 5
Solution 6
Solution 7 Chris Esler