nativeElement.classList.add()替代方案

Bak*_*Gat 12 typescript angular

我正在尝试以角度2创建按钮组件.在主机上,我必须设置动态生成的css类名.(取决于绑定属性)

主机上的'[ngClass]'不起作用.

我已经读过使用elementRef.nativeElement.classList.add(value)也不是最好的方法,因为webworkers(或左右)不支持classList

在主机上动态生成类的最佳选择是什么?

@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){}
} 
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 12

@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){}
} 
Run Code Online (Sandbox Code Playgroud)


Bak*_*Gat 8

感谢Günter我找到了解决方案.这是他的代码,但为将来可以使用它的任何人清理.

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) { }
Run Code Online (Sandbox Code Playgroud)