2016-03-17 5 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 крючок:

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: Инициализировать директиву/компонент после Угловой инициализирует ввод данных переплета свойства.

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'); 
     } 
    } 
} 
Смежные вопросы