nativeElement.classList.add()替代 [英] nativeElement.classList.add() alternative

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

问题描述

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

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]"不起作用.

'[ngClass]' on host does not work.

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

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)

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆