Is it possible to add a dynamic class to host in Angular 2?
The Renderer
s 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){}}
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'; }}
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;}