垫自动完成-显示名称,但保存用户ID值

时间:2019-12-04 21:10:44

标签: angular typescript autocomplete angular-material

我正在尝试实现自动完成功能,但是我想将所选的用户ID保存在数据库中。

也就是说,在自动完成功能中,我想显示要选择的用户名,但是作为返回值,我不希望该名称,而是它的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>

1 个答案:

答案 0 :(得分:1)

您绝对希望拥有对象流,而不是this.filteredFruits中的字符串。在当前代码库的情况下,您将不得不查找所选字符串的ID,这听起来很脆弱-最好不要将键/值对彼此分开,否则当使用错误的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选项:

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

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