Angular: How to capture checkbox status on change

Viewed 131

Im a Angular newbie. There are three check boxes in my component. When the checked status changes in each one, I need to get the checked status of all three checkboxes.

        <div class="mb-15 p-0 ">
            <div class="col-2 p-0 font-700 font-12">
                <mat-checkbox (change)="onChange1($event)">
                </mat-checkbox>
            </div>
        </div>
        <div class="mb-15 p-0 ">
            <div class="col-2 p-0 font-700 font-12">
                <mat-checkbox (change)="onChange2($event)">
                </mat-checkbox>
            </div>
        </div>
        <div class="mb-15  p-0 ">
            <div class="col-2 p-0 font-700 font-12">
                <mat-checkbox (change)="onChange3($event)">
                </mat-checkbox>
            </div>
        </div>

Depending on the check box statuses, have to do a small logic inside my method and send a POST call to the WEB API.

What's the best way to capture all three checkbox statuses on any single checkbox status change? Appreciate some help on this.

1 Answers

You can use ReactiveForms for this purpose.

Demo

https://stackblitz.com/edit/angular-ivy-nauyv1?file=src%2Fapp%2Fapp.component.ts

Code

ts

form: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.form = this.fb.group({
    /**
     * initial checkbox values
     */
    checkboxes: this.fb.array([false, false, false])
  });

  this.form.valueChanges
    .subscribe(v => {
      /**
       * You get the status change here
       */
      console.log(v);
    });
}

get checkboxes() {
  return (this.form.get("checkboxes") as FormArray).controls;
}

html

<form [formGroup]="form">
  <form formArrayName="checkboxes">
    <div *ngFor="let cb of checkboxes; let i = index">
      <input type="checkbox" [formControlName]="i">
    </div>
  </form>
</form>

You can replace the input with your mat-checkbox above.

Note

Make sure to import ReactiveFormsModule

Reference

https://angular.io/guide/reactive-forms

Related