[英]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;
}
}
}
即使禁用屬性出現在 DOM 中,墊子按鈕也不會完全更新(禁用的 styles 丟失,因為 angular 材料對墊子按鈕具有的一些禁用類也從 DOM 中丟失)。 所以mat-button不會更新。 對此有什么建議嗎?
你的堆棧閃電戰和問題是不同的。 我已經對您要查找的內容做出了最好的猜測。
此處使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.