0

I am trying to disable button and input-field through angular directive based on the permission. I have tried few ways but it doesn't help

if (this.permission==true) {
      this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
          const viewRootElement : HTMLElement = this.viewContainer.createEmbeddedView(
            this.templateRef
          ).rootNodes[0];
          viewRootElement.setAttribute('disabled', 'false');

        }
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Jeyam Thillai
  • 71
  • 2
  • 12

3 Answers3

1
  1. For the Reactive Forms usage you may use directive for that
@Directive({
  selector: '[disableControl]'
})
export class DisableControlDirective implements OnChanges {
  @Input() disableControl = false;

  constructor(private ngControl: NgControl) {}
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['disableControl'] && this.ngControl.control) {
      const action = this.disableControl ? 'disable' : 'enable';
      this.ngControl.control[action]();
    }
  }
}

Now you can use it on input or button

<input [formControl]="formControl" [disableControl]="disable">
<button (click)="disable = true">Disable</button>
<button (click)="disable = false">Enable</button>
  1. For the usual input you should just use [readonly] - it will be both reactive and working (see explanation why disabled is bad here)
Lonli-Lokli
  • 3,357
  • 1
  • 24
  • 40
0

For the button disabled you can use this:

<button class="btn btn-primary" type="submit" [disabled]="disablebtn" (click)="submit()">Upload</button>

In .ts file:

disablebtn:boolean=false;
submit(){
this.disablebtn=true;
}

For the input field you can use this:

<input type="text" [disabled]="true">
0

First: you want to create a directive, which targets button and input.

@Directive({
  selector: 'input[dis], button[dis]',
})

Next: you need to know how to toggle the disable state of a button/input

this.render.setProperty(
            this.el.nativeElement,
            'disabled',
            true //false
          );

Last: in that directive, use your permission service to toggle the element state, in this case is disable state.

this.perService.permission$
      .pipe(
        tap((hasPermission) => {
          //get permission value and set the disable state
          );
        })
      )

You can find the full working code in the below link.
Working stackblitz

Jimmy
  • 1,276
  • 7
  • 8