单击后,选择Angular 5删除选项

时间:2018-03-05 12:32:39

标签: arrays angular select

我有两个数组:

availableTargets: [ {id: 1, name: "Target 1"}, {id: 2, name: "Target 2"}, {id: 3, name: Target 3" ];
selectedTargets: [];

我创建了一个多选列表:

<select multiple>
    <option *ngFor="let target of availableTargets" [value]="target .id" (click)="AddTarget($event)">{{target.name}}</option>
 </select>

当用户点击某个选项时,我想将'Target'添加到selectedTarget数组并将其从availableTargets数组中删除。

public AddTarget(event) {
    let id = event.target.id;
    this.availableTargets = this.availableTargets .filter(function (el) { return el.id != id });
    this.selectedTargets.push(event.target.id);
  }

从availableTarget数组中删除元素后,我的多选列表不会更新。我该如何触发?

1 个答案:

答案 0 :(得分:2)

您只需使用索引

即可

模板方:

<select multiple>
    <option *ngFor="let target of availableTargets; let i = index;" [value]="target .id" (click)="AddTarget(i)">{{target.name}}</option>
</select>

组件方:

  public AddTarget(index) {
    this.selectedTargets.push(this.availableTargets[index]);
    this.availableTargets.splice(index, 1);
  }

<强> WORKING DEMO