21

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.
      ...
});
2
  • 1
    Try patchValue({amateur: false}) (single value instead of array) Commented Dec 28, 2017 at 1:40
  • 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. Thanks Commented Dec 28, 2017 at 1:48

2 Answers 2

39

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>
Sign up to request clarification or add additional context in comments.

1 Comment

You are also correct. Silly me just cut and pasted the formbuilder code with the arrays in it, instead of the values. Thank you.
0

You also try this way:

component.ts

showClassGrp: FormGroup;
construct(private formBuilder: FormBuilder){}

ngOnInit() {
  this.showClassGrp = this.formBuilder.group({
    amateur: [false]
  });

  this.showClassGrp.patchValue({ 
    amateur: true,
  }
  console.log(this.showClassGrp.value.amateur);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.