Angular 5 reactive form set mat-checkbox to check

Darryl Wagoner WA1GON picture Darryl Wagoner WA1GON · Dec 28, 2017 · Viewed 46.5k times · Source

I am trying to use mat-checkbox with reactive forms on Angular 5.1.2 and Angular Material 5.0.2.

Everything is working well except that when I use patchValue({amateur: [false]) it is still checked. What is weird is I have other forms where I am doing the same thing and they work fine. It also isn't just the amateur checkbox, it is all the checkboxes are checked. Just using "amateur" as an example.

The formControl amateur.value is always false. However once the patched value is executed, the control is checked.

What am I missing?

HTML5

 <form [formGroup]="showClassGrp">
   <mat-checkbox id="amateur" class="amateur" color="primary" 
      formControlName="amateur">Amateur</mat-checkbox>
 </form>

TypeScript

FormBuilder works and display is correct.

this.showClassGrp = this.fb.group({

  ...
  amateur: [false],
  ...
});

patch showClassGrp and all the checkboxes are checked even thou the formControl value for them are false.

    this.showClassGrp.patchValue({
      className: [this.showClass.className],  //this works
      amateur: [false],  // this changed the display to checked.
      ...
});

Answer

Iancovici picture Iancovici · Dec 28, 2017

If you're using reactive from, you may want to assign a FormControl to each member in the form. Something like this

component.ts

  showClassGrp: FormGroup;

  constructor() { }

  ngOnInit() {


    this.showClassGrp = new FormGroup({
      'amateur': new FormControl(false),
    });

  }

  onSubmit(){
    console.log(this.showClassGrp.value.amateur);
    this.showClassGrp.patchValue({amateur: false});
    console.log(this.showClassGrp.value.amateur);
  }

component.html

<form [formGroup]="showClassGrp" (ngSubmit)="onSubmit()">
  <mat-checkbox id="amateur" class="amateur" color="primary"
                formControlName="amateur">Amateur</mat-checkbox>
  <button class="btn btn-primary" type="submit"> Submit </button>
</form>