angulartypescriptangular-materialangular7custom-directive

Custom Diasble Directive not working angular


I'm trying to create a custom directive for disabling a form field but it's not working.

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

@Directive({
  selector: '[appCustomDisable]',
  })
 export class CustomDisableDirective {
@Input() appCustomDisable: boolean;
constructor(private el: ElementRef, private renderer: Renderer2) {}

ngOnChanges() {
if (this.appCustomDisable) {
  this.renderer.setProperty(this.el.nativeElement, 'disabled', 
this.appCustomDisable);
} else {
  this.renderer.setProperty(this.el.nativeElement, 'disabled', 
this.appCustomDisable);
 }
}
}

I also tried the above using Render from '@angular/core'

 this.renderer.setElementAttribute(this.el.nativeElement, 'disabled', 
'true');

in app.component.html I'm using like [appCustomDisable]="myVar"

Stackblitz link https://stackblitz.com/edit/angular-lxb661


Solution

  • Since your are using MatInput your Code wont work for that. But you can adapt it simply like:

    import { Directive, ElementRef, Input, Renderer2, Optional, S } from '@angular/core';
    import { MatInput } from '@angular/material'
    
    @Directive({
      selector: '[appCustomDisable]'
    })
    export class CustomDisableDirective {
      @Input() appCustomDisable: string;
      constructor(@Optional() private matInput: MatInput, private el: ElementRef, private renderer: Renderer2) { }
    
      ngOnChanges() {
        // Find Input
        let input: any;
        if (this.matInput) {
          // It's a Material Input
          input = this.matInput;
        }
        else {
          // Its a native Input
          if (this.el.nativeElement && this.el.nativeElement.tagName && this.el.nativeElement.tagName === "INPUT") {
            input = this.el.nativeElement;
          } else {
          // No Input found
          // return or throw error
          return;
          }
        }
    
        if (this.appCustomDisable === 'hide') {
          this.renderer.setStyle(this.el.nativeElement, 'display', 'none')
        } else if (this.appCustomDisable === 'view') {
         console.log(input);
         input.disabled = true;
        }
        else {
          this.renderer.setStyle(this.el.nativeElement, 'display', 'block')
        }
      }
    

    }