I'm using Angular 11 and a form with a form group. I have several fields in my form, which I want to set enabled/disabled depending on outer circumstances. This works for input fields as expected.
I made a simple example on stack blitz: https://stackblitz.com/edit/my-cb-test?file=src/app/app.component.html
What I did, I have my app-component.ts:
import { Component, VERSION } from "@angular/core";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
bvalue = true;
disbled = false;
form: FormGroup;
constructor(private fb: FormBuilder) {
this.buildFormGroup(this.disbled);
}
buildFormGroup(dis: boolean): void {
this.form = this.fb.group({
firstCB: [
{ value: this.bvalue, disabled: dis },
[Validators.requiredTrue]
],
inputField: [{ value: "Test", disabled: dis }, [Validators.required]]
});
}
switch(): void {
this.disbled = !this.disbled;
console.log("Disabled: " + this.disbled);
this.buildFormGroup(this.disbled);
}
}
and my html:
<form [formGroup]="form">
<div>
<mat-checkbox formControlName="firstCB">
Checkbox
</mat-checkbox>
</div>
<mat-form-field>
<input matInput formControlName="inputField" type="text" />
</mat-form-field>
<button (click)="switch()">Click</button>
</form>
When I click the button the input field gets enabled/disabled as expected but the checkbox stays enabled (or more precise on the first state it had).
Any idea whats wrong here?
EDIT: I know I can use [disabled]="condition" in HTML but this is considered as bad practice and gives a warning in console...