1

I am trying to add values to an array if checkbox is checked and remove if it isn't. Following is my HTML code:

<div *ngFor="let item of checkListFilter">
    {{item.name}}
</div>
<input type="checkbox" id="test" (click)="pushCheckBoxValue(this.id)">

Typescript code:

  checkListFilter = [
    { id: 1, name: "ABC" },
    { id: 2, name: "XYZ" },
    { id: 3, name: "DEF" },
  ]
  pushCheckBoxValue(value: any) {
    this.checkListFilter.push(value)
  }
Atif Azad
  • 697
  • 2
  • 9
  • 21

2 Answers2

1

To have checkbox for each element you have to re-organize your html like this

<div *ngFor="let item of checkListFilter">
  {{ item.name }}
  <input type="checkbox" id="test" (click)="pushCheckBoxValue(item)" />
</div>

With this aproach your code will work, but you will have duplicated values inside your checkListFilter array.

Your optimal solution would be to use Reactive Forms like answered here: https://stackoverflow.com/a/40937827/12677894

Dimitar Cetelev
  • 364
  • 1
  • 9
  • Thank you for your answer i got solution from https://stackblitz.com/edit/angular-tpvhh5?file=src%2Fapp%2Fapp.component.ts – Atif Azad May 19 '22 at 06:04
1

Typescript code:

  checkListFilter = [
    { id: 1, name: "ABC",isChecked:false },
    { id: 2, name: "XYZ",isChecked:false },
    { id: 3, name: "DEF",isChecked:false },
  ]
get checkedIds(){

let ids =[];
let checkListFilter = this.checkListFilter;
ids = checkListFilter.filter(item=>isChecked).map(item=>item.id);

}

Html:

<div *ngFor="let item of checkListFilter">
    {{item.name}}
<input type="checkbox" id="test" 
         [(ngModel)]="item.isChecked"
>
</div>

For each change checkedIds will be changed: console.log(this.checkedIds)// [1,2]........

Zrelli Majdi
  • 1,204
  • 2
  • 11
  • 16
  • Thank you for your answer i got solution from https://stackblitz.com/edit/angular-tpvhh5?file=src%2Fapp%2Fapp.component.ts – Atif Azad May 19 '22 at 06:03