我的自动完成显示来自具有此定义的对象的值:
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”值?
最佳答案
你必须做两件事。
[value]
绑定(bind)到 id
而不是对象。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/