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)
  }
3
  • I highly recommend checking this for a basic understanding on <input type="checkbox" /> Commented May 18, 2022 at 12:45
  • Why are you passing and ID? Commented May 18, 2022 at 12:46
  • I will display the id number also Commented May 18, 2022 at 12:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer i got solution from stackblitz.com/edit/…
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]........

1 Comment

Thank you for your answer i got solution from stackblitz.com/edit/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.