Home > Enterprise >  Access mat-raised-button disabled attribute
Access mat-raised-button disabled attribute

Time:08-31

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

This is one hacky Solution that worked for me:

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

Now i implemented the Solution provided by Chellappan வ

  • Related