jeudi 17 février 2022

Push only checked and not duplicated checkbox values to an array in Angular?

I have three checkboxes and I want to create an array which should have the values of the checked checkboxes values and should avoid pushing duplicating values.

This is what I have tried but values are pushing even though it is checked or not.

Can someone let me know what is the issue here?

.ts

dataSourceChange(event:any){

    var name = event.target.name;
    var isChecked = event.target.checked;
    const index = this.dataSource.findIndex((el) => el.id === name);

    if (index > -1) {
      this.dataSource[index].isChecked = isChecked;
    } else {
      this.dataSource.push(name);
    }
    this.dataSource = [...this.dataSource];
    console.log(this.dataSource);
  }

.html

 <input type="checkbox" name="om" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> OM</span>
 <input type="checkbox" name="fe" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> FE</span>
 <input type="checkbox" name="be" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> BE </span>



Aucun commentaire:

Enregistrer un commentaire