Angular2 - 在检查时将选中的值推送到数组

时间:2017-07-13 15:42:41

标签: angular typescript

我有一个组件,它接收员工记录的对象并将其显示在表格中。每个记录都有一个复选框,允许您选择"员工将被纳入下一个流程。

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

在这个组件中,我创建了一个数组selectedEmployees = [];,我的目标是当我单击一个复选框时,它的值被推送到数组,当我取消选中它时,该值将从数组中删除

我尝试将ngModel用于2 way binding,但由于此数据在对象中没有初始检查值,因此我无法正常工作。

ngModel是实现这一目标的最佳方式吗?也许我只是走错路。

我尝试关注this question,但打字稿引发了一条错误消息,指出.entries无效。可能是旧版的角度?

1 个答案:

答案 0 :(得分:2)

您可以在复选框中添加click事件,并将其传递给处理添加或删除的函数。

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

我已经扩展了演示,包括通过共享服务与兄弟组件共享selectedEmployees

相关问题