18
votes

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.
      ...
});
1
Try patchValue({amateur: false}) (single value instead of array)Harry Ninh
You are so right! I knew it was something stupid, but I just couldn't see it. As soon as I read you answer I knew where I went wrong. ThanksDarryl Wagoner WA1GON

1 Answers

32
votes

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>