【问题标题】:MatAutocomplete value X displayMatAutocomplete 值 X 显示
【发布时间】:2019-08-11 13:21:23
【问题描述】:

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

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

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

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

如何才能只获取 formControl 中的“id”值?

【问题讨论】:

  • 附带说明,&lt;mat-autocomplete 代码行中不需要 .bind(this)。该函数不使用this
  • @Igor,好的。我是在官方代码中使用的。

标签: angular angular-material


【解决方案1】:

你必须做两件事。

  1. 更新模板,使[value] 绑定到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;
}

【讨论】:

    【解决方案2】:

    FormControl 接收整个项目,因为您将每个 &lt;mat-option&gt;[value] 属性绑定到整个项目。

    只有 id 被传递给 FormControl 替换:

    &lt;mat-option *ngFor="let item of filteredOptions" [value]="item"&gt;

    &lt;mat-option *ngFor="let item of filteredOptions" [value]="item.id"&gt;

    正如 Igor 所说,您需要更新您的 displayFn 函数以显示 Person 的名称。

    【讨论】:

    • 不起作用。这样做,它会在我选择一个项目后在输入元素中显示“id”。
    猜你喜欢
    • 2019-03-20
    • 2018-07-23
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多