Frank
Frank

Reputation: 34

Angular 11 Form disabled on Checkbox/Radiobuttons

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...

Upvotes: 1

Views: 2064

Answers (1)

TotallyNewb
TotallyNewb

Reputation: 4820

I didn't have time to dig deeper into the MatCheckbox code, but it seems that it doesn't react to re-assigning of the FormControl binding. If you'd try re-using the same form (and form control) and simply enabling / disabling the whole form (or specific FormControl) you'll see that it gets disabled correctly. Not sure if that's acceptable workaround for you.

Here is updated stackblitz.

Try filing a bug report in angular material repo (or look into code - perhaps it's working as intended).

Adn regarding comments under your question - you should NOT mix disabled attribute with reactive form bindings. This is a bad practice, and will throw warnings when you're serving the application in development (and might cause other issues as well, depending on your use case).

Upvotes: 1

Related Questions