我的自动完成显示具有以下定义的对象的值:
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”值?
你必须做两件事。
- 更新模板,以便
[value]
界限为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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)