角度:使用指令禁用材质按钮不起作用

时间:2019-09-02 07:34:15

标签: javascript angular typescript angular-material

我想通过指令禁用某些按钮(向按钮添加禁用属性)。

此指令适用于经典html按钮,但不适用于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');
  }
}

输出:

enter image description here

请参阅stackblitz: https://stackblitz.com/edit/angular-5xq2wm

1 个答案:

答案 0 :(得分:2)

如果将按钮垫放置在按钮元素上,它将在内部投射到按钮垫组件中。由于它是内容投影,因此无法在构造函数中设置disable true。

尝试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