2

Hy, I need collect selected values through checkbox check's which are in ngFor. Below is the code.

 <tr *ngFor="let item of items; let index = index;">
    <td>{{item.bed}}</td>
    <td>{{item.size}}</td>
    <td>{{item.name}}</td>
    <td>
      <input type="checkbox"
             name="domain-{{item.bed}}"
             [(ngModel)]="items[index].id"
      >
    </td>
  </tr>
<button (click)="OnSelect()">Select</button>

In component, Im trying to access like this.

component.ts
items = [];
ngOnInIt() {
  this.items = somepromise.then((items) => this.items );
}
OnSelect() {
  console.log(this.items);
}

On Select, I see all values of items printed instead of selected check box values. Any thoughts ?

0

1 Answer 1

7
 <td>
    <input type="checkbox"
       name="item-{{item.bed}}"
       #myItem
      (change)="OnCheckboxSelect(item.id, $event)"
     >
 </td>

In component:

@ViewChildren('myItem') item;
selectedIds = [];

  OnCheckboxSelect(id, event) {
    if (event.target.checked === true) {
      this.selectedIds.push({id: id, checked: event.target.checked});
      console.log('Selected Ids ', this.selectedIds);
    }
    if (event.target.checked === false) {
      this.selectedIds = this.selectedIds.filter((item) => item.id !== id);
    }
  }

I was able to get what I want in this way.

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

Comments

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.