簡體   English   中英

mat-autocomplete 顯示名稱但獲取 ID 值

[英]mat-autocomplete Display name but get ID Value

我正在使用自動完成(Mat-autocomplete),目前它允許加載“用戶”列表。

在自動完成中,我想顯示用戶名,但我想保存所選用戶 ID 的值。

我有這個:

 this.allFruits = val.map(user => user.username);

我將其更改為獲取所有字段,但是我無法獲取所選用戶 ID 的值,有人可以幫助我嗎?

 this.allFruits = val;

我的代碼演示

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>

成分

 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); //use this to apply changes instantly
      } 
    )
  }

  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);
  }

也許在上述場景中使用 Hashmap 可能是一個好主意

在你的類變量中創建一個新的 Map 如下

allFruits: string[] = [];
nameIdMap =  new Map<string, number>();

現在在初始化 allFruits 時,同時初始化地圖......

 this.allFruits = val.map(user => {
      this.nameIdMap.set(user.username, user.id);
      return user.username
    });

您可以使用 map.get 在如下所述的選定函數中輕松獲取此值

selected(event: MatAutocompleteSelectedEvent): void {
  console.log(this.nameIdMap.get(event.option.viewValue));
  this.fruits.push(event.option.viewValue);
  this.fruitInput.nativeElement.value = '';
  this.fruitCtrl.setValue(null);
}

您不需要編寫太多額外的代碼,也不需要更改任何預運行代碼。 所以我認為這會工作得很好。

暫無
暫無

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

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