簡體   English   中英

Mat-autocomplete - 顯示名稱但保存用戶 ID 值

[英]Mat-autocomplete - Display name but save User ID value

我正在嘗試實現自動完成,但是我想將選定的用戶 ID 保存在數據庫中。

也就是說,在自動完成中,我想顯示要選擇的用戶名,但作為返回值,我不需要名稱,而是它的 ID。

我認為我的問題出在這一行:

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

我的代碼——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 和 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-option *ngFor="let fruit of filteredFruits | async" [value]="fruit.id">    
  {{fruit.name}}
</mat-option>

現在fruitCtrl應該有一個 id 作為值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM