2016-02-19 101 views
5

我想创建一个角度为2的按钮组件。 在主机上,我必须设置一个动态生成的css类名。 (取决于绑定属性)nativeElement.classList.add()替代

主机上的[ngClass]不起作用。

我读过使用elementRef.nativeElement.classList.add(值)是不是最好的方式要么,因为班级名册不支持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){} 
} 
+1

'this.elementRef.nativeElement.className + ='md-'+ this.color_'? – dfsq

回答

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

谢谢@günter-zöchbauer,但是会留下问题。当尝试设置'''myCustomClass'类被'md-accent'重写。两者都应该存在。 – BakGat

+0

我更新了我的答案。我不完全确定是否需要传递'elementRef'或'elementRef.nativeElement'。在最近一次更新后,它对于一些/所有的API都进行了更改,并且我没有检查过,因为如果包含'Renderer',我认为是这样。 –

+0

谢谢,我会在今天晚些时候尝试。 – BakGat

3

由于冈特我已经找到了解决办法。 这是他的代码,但为将来可以使用它的任何人打扫。

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