How to disable angular mat-form-field(input) field using mat-slide-toggle in reactive forms, when slide toggle on input field is true it should be enabled otherwise input field should be disabled.
2 Answers
You can use change method on mat-slide-toggle as
<mat-slide-toggle
(change)="changeDisable()" formControlName="enableWifi">
Enable Wifi</mat-slide-toggle>
<mat-form-field class="demo-full-width">
<input [disabled]="checked" formControlName="FirstName" matInput
placeholder="First Name">
</mat-form-field>
changeDisable() {
if (this.formGroup.controls['FirstName'].disabled) {
this.formGroup.controls['FirstName'].enable() ;
} else {
this.formGroup.controls['FirstName'].disable() ;
}
}
Stackblitz Demo showing Input Disable/Enable on Change of mat toggle
3 Comments
gaus shaikh
Hello sir, your example is good but i want input field disabled when slide off and enabled when slide on.how can achieve this .plz help me.
Abhishek Kumar
@gausshaikh add
this.formGroup.controls['FirstName'].disable(); line in ngOnInit to make input disable at start-up. See, the link now, its updatedgaus shaikh
Thank You Sir,You are Great.
Please try this
in html:
<mat-slide-toggle (change)="toggle($event)">Slide me!</mat-slide-toggle>
<input [attr.disabled]="show ? '' : null"/>{{show}}
in ts:
show: boolean = false;
toggle(e: any) {
e.checked? this.show = true: this.show = false;
}
3 Comments
gaus shaikh
i want disabled not hide.
gaus shaikh
not working sir, i found solution, but it is delay, i want input field disabled onLoad.
Mauricio Gracia Gutierrez
"this.show = e.checked" is a better way anyway