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

Viewed 29027

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

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

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.

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
    ) { }
}
Related