typescript - nativeElement.classList.add() 替代方案

标签 typescript angular

我正在尝试以 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/

相关文章:

typescript - 缓存构造函数导致 "Property ' .. .' has no initializer and is not definitely assigned in the constructor."

javascript - 当存在嵌套组件时,ng-content 从父级作用域中嵌入

Angular HTTP 客户端在拦截器中返回 null

javascript - 如何计算已选中的 mat-radio-button 的数量? Angular

javascript - 为什么我不能在@NgModule 中导入 Angular 2 服务?

angular - 无法绑定(bind)到 'formControl',因为它不是 'input' 的已知属性 - Angular2 Material Autocomplete 问题

javascript - 如何在 Angular html 中动态更新 SVG 图像 href?

angular - ngrx/data error$ stream - 忽略之前的值

javascript - 如何在 typescript 中使用外部javascript库-Angular 4

typescript - 如何在 Props 中指定函数的类型