7

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

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.