我正在尝试以 Angular 2 创建一个按钮组件。 在主机上,我必须设置一个动态生成的 css 类名。 (取决于绑定(bind)属性)
主机上的“[ngClass]”不起作用。
我读过使用 elementRef.nativeElement.classList.add(value) 也不是最好的方法,因为 classList 在 webworkers 上不受支持(或如此)
在主机上动态生成类的最佳选择是什么?
@Component({
selector: '[md-button]',
})
export class MdButton {
color_: string;
@Input
set color() {
this.color_ = value;
if (this.elementRef !== undefined) {
this.elementRef.nativeElement.classList.add('md-' + this.color_);
}
}
get color(): string {
return this.color_;
}
constructor(public elementRef: ElementRef){}
}
最佳答案
@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){}
}
关于typescript - nativeElement.classList.add() 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35506395/