Angular how to get the multiple checkbox values?

Since you have several values you want to use, you need to use an FormArray, since FormControl can only capture one value.

Start with declaring an empty formArray:

this.myForm = this.fb.group({
  useremail: this.fb.array([])
});

Iterate the your emails, and watch for the change event and pass the respective email and event to a method onChange where you check if it’s checked, then add the respective email to the formarray, if it’s unchecked, remove the chosen email from the form array:

<div *ngFor="let data of emails">
  <input type="checkbox" (change)="onChange(data.email, $event.target.checked)"> {{data.email}}<br>
</div>

And onChange:

onChange(email:string, isChecked: boolean) {
  const emailFormArray = <FormArray>this.myForm.controls.useremail;

  if(isChecked) {
    emailFormArray.push(new FormControl(email));
  } else {
    let index = emailFormArray.controls.findIndex(x => x.value == email)
    emailFormArray.removeAt(index);
  }
}

Demo

Leave a Comment