Mat 自动完成 - 删除用户时从数组中删除 ID

Mat autocomplete - Remove ID from array when user is removed

我使用此自动完成功能可以 select 多个用户。

当我 select 一个用户时,我使用推送将 ID 存储在一个变量中。此推送将帮助我保留所有 selected 用户的 ID。

如果您 select 一个用户然后想删除它,推送将包含该用户的 ID :(

有没有一种方法,如果我删除一个用户,该用户 ID 将不会出现或从推送提供的数组中删除?

我存储所有 ID 的地方

 var a = (this.nameIdMap.get(event.option.viewValue));
  this.allIDS.push(a);
   var c = this.allIDS; 
    var b = c.filter(function(value, index){ return c.indexOf(value) == index });
    console.log(b)

DEMO

代码

 remove(fruit: string): void {
    const index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }

 selected(event: MatAutocompleteSelectedEvent): void {
  var a = (this.nameIdMap.get(event.option.viewValue));
  this.allIDS.push(a);
   var c = this.allIDS; 
    var b = c.filter(function(value, index){ return c.indexOf(value) == index });
    console.log(b)
  this.fruits.push(event.option.viewValue);
  this.fruitInput.nativeElement.value = '';
  this.fruitCtrl.setValue(null);
}

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
  }


<mat-form-field class="example-chip-list">
  <mat-chip-list #chipList>
    <mat-chip
      *ngFor="let fruit of fruits"
      [selectable]="selectable"
      [removable]="removable"
      (removed)="remove(fruit)">
      {{fruit}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input
      placeholder="New fruit..."
      #fruitInput
      [formControl]="fruitCtrl"
      [matAutocomplete]="auto"
      [matChipInputFor]="chipList"
      [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
      [matChipInputAddOnBlur]="addOnBlur">
  </mat-chip-list>
  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
    <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
      {{fruit}}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

问题

如您所见,我 select编辑了 3 个用户,然后删除了 1 个。我总共有 2 个用户 select编辑,但是在数组中我有 2 个 [=] 42=]被淘汰的用户+被淘汰用户的id。这个已删除的用户 ID 不应存在 :(

您只需要从 this.allIDs 中删除与从 this.fruits

中删除相同的索引
remove(fruit: string): void {
  const index = this.fruits.indexOf(fruit);
  if (index >= 0) {
    this.fruits.splice(index, 1);
    this.allIDS.splice(index, 1);
  }
}

或者,您可以创建一个对象数组,将每个条目的名称和 ID 作为一个对象保存。