Alec Sibilia Alec Sibilia - 2 months ago 38
AngularJS Question

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

I know 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 how you would with NgClass. Like this:

@Component({
selector: 'selector-el',
host: {
'[NgClass]': 'colorClass'
},
...
})
...
constructor(){
this.colorClass = 'red';
}


(I know NgClass is not actually supported, looking for possible solutions)

Answer

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