I\'m trying to create a button component in angular 2. At the host I have to set a dynamically generated css classname. (depending on binded property)
\'[ngClass]\'
Thanks to Günter I've found the solution. This is his code but cleaned for anyone who can use it in the future.
private color_: string;
@Input()
set color(value: string) {
this.color_ = value;
this.renderer.setElementClass(this.elementRef, 'md-' + this.color_, true);
}
get color(): string {
return this.color_;
}
constructor(private elementRef: ElementRef, private renderer: Renderer) { }
@Component({
selector: '[md-button]' //,
// host: { '[class]': 'classList()' }
})
export class MdButton {
color_: string;
// classList() {
// return 'md-' + this.color_;
// }
@Input
set color() {
this.color_ = value;
// if (this.elementRef !== undefined) {
// this.elementRef.nativeElement.classList.add('md-' + this.color_);
// }
this.renderer.setElementClass(this.elementRef, 'md-' + this.color_, true);
}
get color(): string {
return this.color_;
}
constructor(public elementRef: ElementRef, private renderer: Renderer2){}
}