2016-03-17 23 views
3

我有這個在我的指令,名爲 'BGCOLOR':Angular2 ElementRef nativeElement檢查是否元素被禁用

export class BgColorDirective { 
    constructor(el: ElementRef) { 
     console.log(el.nativeElement.disabled); // show "false" 
     if (el.nativeElement.disabled) { 
      el.nativeElement.style.backgroundColor = '#5789D8'; 
      el.nativeElement.style.color = '#FFFFFF'; 
     } 
    } 

在我的模板,我有:

<button (click)="submitData()" [disabled]="true" bgcolor [routerLink]="['Onboarding']"> </button> 

我不understant爲什麼el.nativeElement.disabled回報false

回答

4

我認爲你需要等待綁定解決。例如,通過構造函數的代碼移動到ngOnInit鉤:從https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

export class BgColorDirective { 
    constructor(private el: ElementRef) { 
    } 

    ngOnInit() { 
    console.log(this.el.nativeElement.disabled); // show "true" 
    if (this.el.nativeElement.disabled) { 
     this.el.nativeElement.style.backgroundColor = '#5789D8'; 
     this.el.nativeElement.style.color = '#FFFFFF'; 
    } 
    } 
} 

作爲提醒:

ngOnInit:初始化指令/組件角初始化數據綁定輸入後屬性。

1

嘗試做相同的ngAfterViewInit方法:

export class BgColorDirective { 
    constructor(private el: ElementRef) {} 
    ngAfterViewInit():void { 
     console.log(this.el.nativeElement.disabled); 
     if (this.el.nativeElement.disabled) { 
      this.el.nativeElement.style.backgroundColor = '#5789D8'; 
      this.el.nativeElement.style.color = '#FFFFFF'; 
     } 
    } 
} 
4

請不要直接使用nativeElement,請使用Renderer代替。

export class BgColorDirective { 
    constructor(el: ElementRef, renderer: Renderer) { 

     if (yourCondition) { 
      renderer.setElementStyle(el.nativeElement, 'background-color', '#5789D8'); 
      renderer.setElementStyle(el.nativeElement, 'color', '#FFFFFF'); 
     } 
    } 
}