I want to disable some buttons through a directive (add disabled property to button).
This directive works on classic html button but doesn't works with angular material design button (mat-button):
import { Component, Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[myDisableButton]'
})
export class HideCantEditDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
// try with Renderer2
this.renderer.setProperty(this.el.nativeElement, 'disabled', true);
// try with ElementRef
this.el.nativeElement.disabled = true;
this.renderer.setStyle(this.el.nativeElement, 'border', '2px solid green');
}
}
@Component({
selector: 'my-app',
template: `
<button mat-button myDisableButton (click)="onClick()">Material Button</button><br /><br />
<button myDisableButton (click)="onClick()">Classic Button</button>`,
styles: [ 'button:disabled { border: 2px solid red !important; }' ]
})
export class AppComponent {
onClick(){
alert('ok');
}
}
Output:
See on stackblitz: https://stackblitz.com/edit/angular-5xq2wm
If you place mat-button on button element it will be content projected into mat-button component internally. since it is content projected you are not able to set disable true in constructor.
Try AfterViewInit
import { Component, Directive, ElementRef, Renderer2, AfterViewInit } from '@angular/core';
@Directive({
selector: '[myDisableButton]'
})
export class HideCantEditDirective implements AfterViewInit {
constructor(private el: ElementRef, private renderer: Renderer2) {
// try with Renderer2
this.renderer.setProperty(this.el.nativeElement, 'disabled', true);
}
ngAfterViewInit(){
// try with ElementRef
this.el.nativeElement.disabled = true;
this.renderer.setStyle(this.el.nativeElement, 'border', '2px solid green');
}
}
Forked Example
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