简体   繁体   中英

Angular Autocomplete - Remove element from list when it is selected

I am trying to develop an autocomplete. My problem is that I can't remove an element from the list when it is selected.

The picture illustrate my problem

图片

I selected a name and then that same continuous name n dropdown :( it should "disappear" when it is selected

My Code --Stackblitz

Stackbiltz

Component

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>

Exclude the selected fruits with ngIf like this:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM