本文介绍了寻找nativeElement.classList.add()替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创造2角一个按钮组件。
在主机我必须设置一个动态生成的CSS类名。 (取决于绑定属性)

[ngClass]'主机不工作。

我读过使用elementRef.nativeElement.classList.add(值)是不是最好的方式不是,因为班级列表不支持webworkers(左右)

什么是动态生成主机?类我最好的选择

  @Component({
    选择:[MD-键]',
})
出口类MdButton {
    color_:字符串;    @input
    设置颜色(){
        this.color_ =价值;
        如果(this.elementRef!==未定义){
            this.elementRef.nativeElement.classList.add(MD-'+ this.color_);
        }
    }    获得色彩(){字符串
        返回this.color_;
    }    构造函数(公共elementRef:ElementRef){}
}


解决方案

  @Component({
    选择:[MD-按钮]'//
    //主机:{'[类]':'班级名册()}
})
出口类MdButton {
    color_:字符串;    //班级名册(){
    //返回'MD-'+ this.color_;
    //}    @input
    设置颜色(){
        this.color_ =价值;
        //如果(this.elementRef!==未定义){
        // this.elementRef.nativeElement.classList.add('MD-'+ this.color_);
        //}        this.renderer.setElementClass(this.elementRef,'MD-'+ this.color_,真正的);
    }    获得色彩(){字符串
        返回this.color_;
    }    构造函数(公共elementRef:ElementRef,私人渲染:渲染器){}
}

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]' on host does not work.

I've read that using elementRef.nativeElement.classList.add(value) is not the best way either, because classList is not supported on webworkers (or so)

What are my best options to generate the class dynamically on host?

@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: Renderer){}
} 

这篇关于寻找nativeElement.classList.add()替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 15:57