Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ElementRef nativeElement check if element is disabled

I have this in my directive, named '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

like image 644
Raph Avatar asked Mar 17 '16 10:03

Raph


3 Answers

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:

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:

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

like image 57
Thierry Templier Avatar answered Oct 14 '22 02:10

Thierry Templier


Don't use nativeElement directly, use Renderer instead.

export class BgColorDirective {
    constructor(el: ElementRef, renderer: Renderer) {

        if (yourCondition) {
            renderer.setElementStyle(el.nativeElement, 'background-color', '#5789D8');
            renderer.setElementStyle(el.nativeElement, 'color', '#FFFFFF');
        }
    }
}
like image 39
Eric Martinez Avatar answered Oct 14 '22 03:10

Eric Martinez


try to do the same in the ngAfterViewInit method :

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';
        }
    }
}
like image 1
Michael Desigaud Avatar answered Oct 14 '22 03:10

Michael Desigaud