【问题标题】:Mat autocomplete - Remove ID from array when user is removed垫自动完成 - 删除用户时从数组中删除 ID
【发布时间】:2020-05-09 03:19:50
【问题描述】:

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

当我选择一个用户时,我使用推送将 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)

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>

问题

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

【问题讨论】:

    标签: angular typescript autocomplete mat-autocomplete


    【解决方案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 保存为一个对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-27
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      相关资源
      最近更新 更多