Partial code:
@Component({
selector: "form-test",
template: `
<form [formGroup]="form">
<input type="checkbox" formControlName="checkbox" />{{ item.name }}
<p>form checkbox disabled: {{ form.get("checkbox").disabled }}</p>
</form>
`,
})
export class FormTestComponent implements OnChanges {
@Input() item: any;
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({});
}
ngOnChanges(changes: SimpleChanges): void {
this.form = this.fb.group({
name: [""],
checkbox: [false],
});
if (this.item.name === 111) {
this.form.get("checkbox")?.disable();
}
}
}
I'll assign a new group to this.form each time ngOnChanges is triggered, and I'll make the disabled property of the checkbox true when this.item.name === 111, but when I click on the other list items, the disabled property of the checkbox will still look like it is true, it's actually false, but the checkbox in the template renders out with disabled=true
In Angular 12, the
disabledattribute in the form state object only sets how the control is initialized and does not bind it nor change it as the value changes.You're initializing the form control with a value and setting its
disabled, but when you change the value ofthis.item.name, thedisabledattribute does not update. This is why the checkbox renders out withdisabled=trueeven though the form control is actually enabled.If so, use
enable()anddisable()methods of the form control to change its disabled state.