Angular 角度自动完成-选中元素后将其从列表中删除

Angular 角度自动完成-选中元素后将其从列表中删除,angular,typescript,autocomplete,Angular,Typescript,Autocomplete,我正在尝试开发一个自动完成。我的问题是,当选中某个元素时,我无法将其从列表中删除 这幅画说明了我的问题 我选择了一个名称,然后是相同的连续名称n下拉列表:(当它被选中时应该“消失”) 我的代码——Stackblitz 组件 constructor(private userService: UserService) { this.filteredFruits = this.fruitCtrl.valueChanges.pipe( startWith(null),

我正在尝试开发一个自动完成。我的问题是,当选中某个元素时,我无法将其从列表中删除

这幅画说明了我的问题

我选择了一个名称,然后是相同的连续名称n下拉列表:(当它被选中时应该“消失”)

我的代码——Stackblitz

组件

constructor(private userService: UserService) {
    this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
        startWith(null),
        map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
  }

  ngOnInit() {
    this.userService.getUsers().subscribe(
      (val: any[]) =>{
        this.allFruits = val.map(user => user.username);
        this.fruitCtrl.setValue(null); 
      } 
    )
  }

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

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

  selected(event: MatAutocompleteSelectedEvent): void {
    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);
  }
HTML

<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"
      (matChipInputTokenEnd)="add($event)">
  </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>

{{水果}
取消
{{水果}

使用ngIf排除所选水果,如下所示:

<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
  <ng-container *ngFor="let fruit of filteredFruits | async">
    <mat-option *ngIf="!fruits.includes(fruit)" [value]="fruit">
      {{fruit}}
    </mat-option>
  </ng-container>
</mat-autocomplete>

{{水果}

你提供了stackblitz的图像。你能给我们一个实际stackblitz的链接吗?@ConnorsFan抱歉!!!我已经更新了链接:(谢谢。但是有白色/空白的条目,如果添加的芯片是用空白值创建的