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

新手上路,请多包涵

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

原文由 Raph 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 487
2 个回答

我认为您需要等待绑定得到解决。例如,通过将构造函数的代码移动到 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';
    }
  }
}

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

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

原文由 Thierry Templier 发布,翻译遵循 CC BY-SA 3.0 许可协议

不要直接使用 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');
        }
    }
}

原文由 Eric Martinez 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题