angular - MatAutocomplete 值 X 显示

我的自动完成显示来自具有此定义的对象的值:

export class Person {
  id: number;
  name: string;
  cityName: string;
}

这是自动完成模板:

<mat-form-field class="example-full-width">
  <input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto">

  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
      <mat-option *ngFor="let item of filteredOptions" [value]="item">
        {{ item.name }}
      </mat-option>
  </mat-autocomplete>
</mat-form-field>

这是 displayWith 函数:

displayFn(value?: any) {
  return value ? value.name : undefined;
}

它可以工作,但是绑定(bind)到这个自动完成的 formControl 接收整个项目对象:

 {
    id: 1;
    name: "John";
    cityName: "Dallas";
 }

如何在 formControl 中只获取“id”值?

最佳答案

你必须做两件事。

  1. 更新模板,使 [value] 绑定(bind)到 id 而不是对象。
  2. 更新 displayFn,以便使用传入的 id 查找对象并返回随后将显示在输入中的名称。
<mat-form-field class="example-full-width">
  <input type="text" placeholder="Person" aria-label="Person" matInput formControlName="personId" [matAutocomplete]="auto">

  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
      <mat-option *ngFor="let item of filteredOptions" [value]="item.id">
        {{ item.name }}
      </mat-option>
  </mat-autocomplete>
</mat-form-field>
displayFn(value?: number) {
  return value ? this.filteredOptions.find(_ => _.id === value).name : undefined;
}

https://stackoverflow.com/questions/55267701/

相关文章:

bash - 如何获取 `ls` 命令的前 n 行

amazon-web-services - 如何在 SQS 队列下添加超过 20 个策略语句 - 权

ruby-on-rails - 捆绑安装不适用于 bundler 2.0.1 的 rails-4.2

list - Haskell:列表操作

hibernate - 当我从 POST 方法更新它时,@CreationTimestamp 列设置

csv - 将 CSV 文件导入为矩阵

python - MacOS 构建问题 lstdc++ not found while buildi

sql - 根据一列删除 Select 查询中的重复项

java - 如何用 java 将换行符替换为 "\n"?

java - 修复 Java newInstance() 已弃用