Mat-autocomplete - 显示名称但保存用户 ID 值

Mat-autocomplete - Display name but save User ID value

我正在尝试实现自动完成,但是我想在数据库中保存 selected 用户 ID。

也就是说,在自动完成中我想将用户名显示为 select,但作为 return 值我不想要名称,而是它的 ID。

我认为我的问题出在这一行:

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

我的代码--Stackblitz

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>

您肯定想要对象流,而不是 this.filteredFruits 中的字符串。使用当前的代码库,您将不得不找到所选字符串的 ID,这听起来很脆弱 - 最好不要将 key/value 对彼此分开,否则在使用错误的 ID 时可能会遇到错误。

this.allFruits = val;

然后更改 this._filter 函数以过滤 object[] 而不是 string[]:

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

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

对于垫子选项:

<mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit.id">    
  {{fruit.name}}
</mat-option>

现在 fruitCtrl 应该有一个 id 作为值