Angular2 ElementRef nativeElement检查元素是否被禁用

Rap*_*aph 5 javascript angular

我的指令名为“ bgcolor”,其中包含以下内容:

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';
        }
    }
Run Code Online (Sandbox Code Playgroud)

在我的模板中,我有:

<button (click)="submitData()" [disabled]="true" bgcolor [routerLink]="['Onboarding']"> </button>
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会el.nativeElement.disabled回来false

Thi*_*ier 5

我认为您需要等待绑定解决。例如,将构造函数的代码移动到ngOnInit钩子中:

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';
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

作为来自https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html的提醒:

ngOnInit:在 Angular 初始化数据绑定输入属性后初始化指令/组件。


Eri*_*nez 5

不要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');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)