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');
}
CodePudding user response:
- 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>
- For the usual input you should just use [readonly] - it will be both reactive and working (see explanation why
disabled
is bad here)
CodePudding user response:
For the button disabled you can use this:
<button 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">
CodePudding user response:
- You want to create a directive, which targets button and input.
- You need to know how to toggle the
disable
state of a button/input - In that directive, use your
permission service
to toggle the element state, in this case is disable state.
I have no idea why I can't format the code so sorry that I cannot provide code here, you can find the code in the below link.
Working stackblitz