jjzjj

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

coder 2025-02-21 原文

我的指令中有这个,名为“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';
        }
    }

在我的模板中,我有:

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

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

最佳答案

我认为您需要等待绑定(bind)被解析。例如,通过将构造函数的代码移动到 ngOnInit Hook 中:

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';
    }
  }
}

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

ngOnInit: Initialize the directive/component after Angular initializes the data-bound input properties.

关于javascript - Angular2 ElementRef nativeElement 检查元素是否被禁用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36057273/

有关javascript - Angular2 ElementRef nativeElement 检查元素是否被禁用的更多相关文章

随机推荐