Access mat-raised-button disabled attribute

400 views Asked by At

i try to access (read) the disabled attribute of a mat-raised-button Button inside of a directive.

If disabled is set true, inside my directive, during ngOnInit, disabled is still false, but the material button is rendered as disabled (grey).

Button:

<button
  my-directive
  mat-raised-button
  [disabled]="isDisabledOrNot()" // returns true
  (click)="doSomething()>bla</button>

My Diective @HostBinding Attempt:

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

I tried using the nativeElement:

export class myDirective implements OnInit {
  constructor(private element: ElementRef, private renderer: Renderer2) {}

  ngOnInit(): void {
    console.log(`disabled:`, this.element.nativeElement.disabled); // prints false

And i used some hack version involved class.mat-button-disabled from github issues but neither works.

I can set the disabled button using the Renderer2 setAttribute method. But that doesn't work for reading.

Any Ideas?

3

There are 3 answers

1
Chellappan வ On BEST ANSWER

Inside your directive you can Inject MatButton class and check whether it is disabled or not

constructor(private button:MatButton){}
  
ngOnInit(){
    console.log(this.button.disabled);
}

Working Example

0
Andresch Serj On

This is one hacky Solution that worked for me:

nativeElement.getAttribute('ng-reflect-disabled') === 'true'

Now i implemented the Solution provided by Chellappan வ

2
AudioBubble On

The disabled attribute of an element is somewhat special, since it doesn't actually hold the values true or false.

If it's false, getAtrribute('disabled') returns null.

If it's true, getAtrribute('disabled') returns (an empty string).

That means one way to check if an element is disabled is to check whether getAttribute('disabled') does not return null.

In Directive form:

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')
    );
  }
}