我想通过一个指令来禁用一些按钮(给按钮添加disabled属性)。
这个指令可以作用于普通的HTML按钮,但是对于Angular Material Design按钮(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');
}
}
输出:
在Stackblitz上查看: https://stackblitz.com/edit/angular-5xq2wm