Home > Back-end >  how to Push Checkbox value to array in typescript angular?
how to Push Checkbox value to array in typescript angular?

Time:05-19

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)
  }

CodePudding user response:

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

CodePudding user response:

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]........

  • Related