lets say that we have a very basic angular reactive form, with two modes: edit and show. And in show mode input fields are disabled, and in edit mode enabled:
<form [formGroup]="formGroup" (ngSubmit)="submitForm()" novalidate>
<label for="fname">First name:</label><br />
<input
type="text"
id="fname"
name="fname"
formControlName="fname"
/><br />
<label for="lname">Last name:</label><br />
<input
type="text"
id="lname"
name="lname"
formControlName="lname"
/><br /><br />
<button type="submit">{{formMode == 'show' ? 'Edit' : 'Submit'}}</button>
</form>
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
formGroup: FormGroup;
formMode: 'show' | 'edit' = 'show';
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.formGroup = this.fb.group({
fname: [{ value: 'John', disabled: this.formMode == 'show' }],
lname: [{ value: 'Doe', disabled: this.formMode == 'show' }],
});
}
submitForm() {
if (this.formMode === 'edit') {
console.log(this.formGroup.value);
this.formMode = "show"
} else {
this.formMode = "edit"
}
}
However when the state od formMode gets toggled from show to edit state, disabled state of the formControls doesn't change.
I know I can use this.formGroup.enable() and this.formGroup.disable(), but the that what be a mess if there was a large form and only some fields are toggling state.
I have expected that this disabled prop to be reactive since this.formMode is reactive by default...
Here is a blitz: https://stackblitz.com/edit/angular-ivy-4zybd7?file=src/app/app.component.ts