简体   繁体   中英

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

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

}

Apparently, what you want to disable is the MatInput directive that is present on the same element. So, just inject it into your component, and disable it:

import { Directive, Input } from '@angular/core';
import { MatInput } from '@angular/material';

@Directive({
  selector: '[appCustomDisable]'
})
export class CustomDisableDirective {

    @Input() appCustomDisable : boolean;
    constructor(private matInput: MatInput) {}

    ngOnChanges() {
        this.matInput.disabled = this.appCustomDisable;
    }

}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM