SBB
SBB

Reputation: 8970

Angular2 - Push checked value to array on check

I have a component that receives an object of employee records and displays them in a table. Each record has a checkbox that allows you to "select" the employee to be included in the next process.

<tr *ngFor="let i of importResults" >
 <td>
  <input type="checkbox"
         value="{{ i.QID }}"
         attr.data-employeename="{{ i.PreferredName }} {{ i.LastName }}"
         [checked]="isSelected" />
  </td>
  <td>{{ i.PreferredName }} {{ i.LastName }}</td>
</tr>

In this component, I created an array selectedEmployees = []; and my goal is that when I click a checkbox, its value is pushed to the array, as well as when I uncheck it, the value is removed from the array.

I tried using ngModel for 2 way binding but because this data doesn't have an initial checked value in the object, I wasn't able to get that working correctly.

Is ngModel the best way to achieve this? Perhaps I was just going about it the wrong way.

I tried following this question but typescript threw an error saying .entries was not valid. It may have been for an older version of angular?

Upvotes: 2

Views: 5241

Answers (1)

Nehal
Nehal

Reputation: 13307

You can add a click event to the checkbox and pass it to a function to handle add or remove.

html:

<div *ngFor="let i of importResults" >
 <div>
  <input type="checkbox"
         value="{{ i.QID }}"
         (click)="change(i)"/>
   <span>{{ i.PreferredName }} {{ i.LastName }}</span>
  </div>
</div>

<p> Selected Employee: {{selectedEmployees | json}} </p>

component.ts:

export class SelectFormExample {
  selectedEmployees = [];

  showSiblingComp = false;

  importResults = [
    {QID: "1", PreferredName: 'Steak', LastName: "Pizza"},
    {QID: "2", PreferredName: 'Cheese', LastName: "Burger"},
    {QID: "3", PreferredName: 'Chicken', LastName: "Panini"}
  ];

  constructor(private service: SharedService){

  }

  change(obj){

    let updateItem = this.selectedEmployees.find(this.findIndexToUpdate, obj.QID));

    let index = this.selectedEmployees.indexOf(updateItem);

    console.log(index);

    if(index > -1){
      this.selectedEmployees.splice(index, 1);
    }
    else{
      this.selectedEmployees.push(obj);
    }

    this.service.setList(this.selectedEmployees);

  }

  findIndexToUpdate(obj) { 
        return obj.QID === this;
  }
}

demo

I have extended the demo to include sharing the selectedEmployees with a sibling component via shared service.

Upvotes: 3

Related Questions