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
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.
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');
}
}
}
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';
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With