Angular material mat-button 不更新来自外部指令的禁用更改

Angular material mat-button doesn't update the disabled change from outer directive

我有一个简单的自定义指令需要禁用该元素。

<button mat-button [myCustomDirective]="'mode1'">Edit</button>

@Directive({
  selector: '[myCustomDirective]'
})
export class MyCustomDirective implements OnInit {
  @Input() myCustomDirective: string;

  @Input()
  @HostBinding('disabled')
  public disabled: boolean;

  constructor(
    private el: ElementRef,
    private cd: ChangeDetectorRef
  ) {}

  ngOnInit() {

    switch (this.myCustomDirective) {
      case 'mode1':
        this.disabled = true;
        this.el.nativeElement.disabled = true;

        setTimeout(() => {
          this.cd.markForCheck();
          this.cd.detectChanges();
        });

        break;

      default:
        this.el.nativeElement.remove();

        break;
    }
  }
}

DEMO

即使 disabled 属性出现在 DOM 中,mat-button 也没有得到完全更新(禁用的样式丢失了,因为 angular material 为 mat-button 设置的一些禁用的 类 在 DOM 中也丢失了。所以 mat-button 不会更新。对此有何建议?

你的 stackblitz 和问题不一样。我已经猜到你在找什么了。

使用 AfterViewInit 的答案 有效。

您还需要添加class mat-button-disabled

import {
  Directive,
  ElementRef,
  Renderer2,
  AfterViewInit,
  Input
} from '@angular/core';

@Directive({
  selector: '[appHasPermissions]'
})
export class HasPermissionsDirective implements AfterViewInit {
  @Input() myCustomDirective: string;

  constructor(private el: ElementRef, private renderer: Renderer2) {
    // try with Renderer2
    this.renderer.setProperty(this.el.nativeElement, 'disabled', true);
  }

  ngAfterViewInit() {
    switch (this.myCustomDirective) {
      case 'mode1':
        // try with ElementRef
        this.el.nativeElement.disabled = true;
        this.renderer.addClass(this.el.nativeElement, 'mat-button-disabled');
        break;
      default:
        this.el.nativeElement.remove();
        break;
    }
  }
}
<button 
  appHasPermissions
  [myCustomDirective]="'mode1'"
  mat-raised-button
  color="warn">
    From directive
</button>

Stackblitz