Javascript Angular2 ElementRef nativeElement 检查元素是否被禁用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36057273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 ElementRef nativeElement check if element is disabled
提问by Raph
I have this in my directive, named 'bgcolor':
我的指令中有这个,名为“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';
}
}
In my template, I have :
在我的模板中,我有:
<button (click)="submitData()" [disabled]="true" bgcolor [routerLink]="['Onboarding']"> </button>
I don't understant why el.nativeElement.disabled
returns false
我不明白为什么el.nativeElement.disabled
回来false
采纳答案by Thierry Templier
I think that you need to wait for the bindings to be resolved. For example by moving the code of your constructor into the ngOnInit
hook:
我认为您需要等待绑定解决。例如,将构造函数的代码移动到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';
}
}
}
As a reminder from https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html:
作为来自https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html的提醒:
ngOnInit: Initialize the directive/component after Angular initializes the data-bound input properties.
ngOnInit:在 Angular 初始化数据绑定输入属性后初始化指令/组件。
回答by Eric Martinez
Don't use nativeElement
directly, use Renderer
instead.
不要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');
}
}
}
回答by Michael Desigaud
try to do the same in the ngAfterViewInit
method :
尝试在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';
}
}
}