MatAutocomplete 值 X 显示 [英] MatAutocomplete value X display
本文介绍了MatAutocomplete 值 X 显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的自动完成显示具有此定义的对象的值:
My Autocomplete shows the values from an object with this definition:
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 函数:
And this is the displayWith function:
displayFn(value?: any) {
return value ? value.name : undefined;
}
它可以工作,但绑定到此自动完成功能的 formControl 接收整个项目对象:
It works, but the formControl binded to this autocomplete receives the entire item object:
{
id: 1;
name: "John";
cityName: "Dallas";
}
如何只获取 formControl 中的id"值?
How can I get only the "id" value in the formControl ?
推荐答案
你必须做两件事.
- 更新模板,使
[value]
绑定到id
而不是对象. - 更新
displayFn
以便使用传入的id
查找对象并返回名称,然后该名称将显示在输入中.
- Update the template so that the
[value]
bounds toid
instead of the object. - Update the
displayFn
so that the passed inid
is used to lookup the object and return the name which will then be displayed in the input.
<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;
}
这篇关于MatAutocomplete 值 X 显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文