{{ item.na" /> {{ item.na" /> {{ item.na"/>

Angular12 ReactiveFormsModule strange phenomenon

54 Views Asked by At

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

enter image description here

enter to demo

1

There are 1 best solutions below

1
Keyboard Corporation On

In Angular 12, the disabled attribute 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 of this.item.name, the disabled attribute does not update. This is why the checkbox renders out with disabled=true even though the form control is actually enabled.

If so, use enable() and disable() methods of the form control to change its disabled state.

ngOnChanges(changes: SimpleChanges): void {
 this.form = this.fb.group({
  name: [""],
  checkbox: [false],
 });

 if (this.item.name === 111) {
  this.form.get("checkbox")?.disable();
 } else {
  this.form.get("checkbox")?.enable();
 }
}