簡體   English   中英

訪問 mat-raised-button 禁用屬性

[英]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屬性有些特殊,因為它實際上並不包含值truefalse

如果為假, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM