【发布时间】: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”值?
【问题讨论】:
-
附带说明,
<mat-autocomplete代码行中不需要.bind(this)。该函数不使用this。 -
@Igor,好的。我是在官方代码中使用的。