[英]Access mat-raised-button disabled attribute
我尝试访问(读取)指令内mat-raised-button
按钮的disabled
属性。
如果 disabled 设置为 true,在我的指令中,在ngOnInit
期间disabled
仍然是false
,但材质按钮呈现为 disabled (灰色)。
按钮:
<button
my-directive
mat-raised-button
[disabled]="isDisabledOrNot()" // returns true
(click)="doSomething()>bla</button>
我的指令@HostBinding 尝试:
export class myDirective implements OnInit {
constructor(private element: ElementRef, private renderer: Renderer2) {}
@HostBinding('disabled')
disabled: any;
ngOnInit(): void {
console.log(`disabled:`, this.disabled); // prints false
我尝试使用nativeElement
:
export class myDirective implements OnInit {
constructor(private element: ElementRef, private renderer: Renderer2) {}
ngOnInit(): void {
console.log(`disabled:`, this.element.nativeElement.disabled); // prints false
我使用了一些涉及class.mat-button-disabled
从 github 问题的黑客版本,但都不起作用。
我可以使用Renderer2
setAttribute
方法设置禁用按钮。 但这不适用于阅读。
有任何想法吗?
在您的指令中,您可以注入MatButton
class 并检查它是否被禁用
constructor(private button:MatButton){}
ngOnInit(){
console.log(this.button.disabled);
}
元素的disabled
属性有些特殊,因为它实际上并不包含值true
或false
。
如果为假, getAtrribute('disabled')
返回null
。
如果为真, getAtrribute('disabled')
返回
(一个空字符串)。
这意味着检查元素是否被禁用的一种方法是检查getAttribute('disabled')
是否不返回null
。
指令形式:
import { AfterViewInit, Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[check-disabled]',
})
export class CheckDisabledDirective implements AfterViewInit {
constructor(private readonly m_element: ElementRef<HTMLElement>) {}
public ngAfterViewInit(): void {
console.log(
`Element is currently ` +
(this.m_element.nativeElement.getAttribute('disabled') === null
? 'not disabled'
: 'disabled')
);
}
}
这是一个对我有用的 hacky 解决方案:
nativeElement.getAttribute('ng-reflect-disabled') === 'true'
现在我实现了Chellappan வ提供的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.