-1

我正在使用此自动完成功能来选择多个用户。

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

如果您选择一个用户然后想要删除它,推送将包含该用户的 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)

演示

代码

 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>

问题

如您所见,我选择了 3 个用户,然后删除了 1 个。我总共选择了 2 个用户,但在数组中我有 2 个选定用户的 id + 被淘汰用户的 id。不应存在​​此已删除的用户 ID :(

图片

4

1 回答 1

1

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 作为一个对象保存。

于 2020-01-22T23:36:26.290 回答