Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: disable material button with directive doesn't works

I want to disable some buttons through a directive (add disabled property to button).

This directive works on classic html button but doesn't works with angular material design button (mat-button):

import { Component, Directive, ElementRef, Renderer2 } from '@angular/core';


@Directive({
  selector: '[myDisableButton]'
})
export class HideCantEditDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    // try with Renderer2
    this.renderer.setProperty(this.el.nativeElement, 'disabled', true);
    // try with ElementRef
    this.el.nativeElement.disabled = true;

    this.renderer.setStyle(this.el.nativeElement, 'border', '2px solid green');
  }
}



@Component({
  selector: 'my-app',
  template: `
  <button mat-button myDisableButton (click)="onClick()">Material Button</button><br /><br />
  <button myDisableButton (click)="onClick()">Classic Button</button>`,
  styles: [ 'button:disabled { border: 2px solid red !important; }' ]
})
export class AppComponent  {

  onClick(){
    alert('ok');
  }
}

Output:

enter image description here

See on stackblitz: https://stackblitz.com/edit/angular-5xq2wm

like image 938
ar099968 Avatar asked Sep 02 '19 07:09

ar099968


1 Answers

If you place mat-button on button element it will be content projected into mat-button component internally. since it is content projected you are not able to set disable true in constructor.

Try AfterViewInit

import { Component, Directive, ElementRef, Renderer2, AfterViewInit } from '@angular/core';


@Directive({
  selector: '[myDisableButton]'
})
export class HideCantEditDirective implements AfterViewInit {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    // try with Renderer2
    this.renderer.setProperty(this.el.nativeElement, 'disabled', true);

  }

  ngAfterViewInit(){
   // try with ElementRef
    this.el.nativeElement.disabled = true;

    this.renderer.setStyle(this.el.nativeElement, 'border', '2px solid green');
  }
}

Forked Example

like image 173
Chellappan வ Avatar answered Oct 04 '22 04:10

Chellappan வ