angular material 自动完成 - 如何显示选定对象的指定 属性
angular material autocomplete - how to display a specified property of selected object
我有一个简单的用例,我在其中循环对象数组。
我想将 属性 "customName" 显示到输入字段,但也能够为 http 调用检索其 ID 值。
<input clrInput [(ngModel)]="order.customer" name="customer [matAutocomplete]="customerAutoComplete"/>
<mat-autocomplete #customerAutoComplete="matAutocomplete" (optionSelected)="onSelectCustomer($event)">
<mat-option *ngFor="let customer of customerList" [value]="customer">
{{customer.customName}}
</mat-option>
</mat-autocomplete>
当我将对象绑定到值时,我可以使用 optionSelected 检索整个对象。但是输入会按预期显示[Object object]。
当我将 customer.customName 绑定到值时,我得到了显示的字符串,但无法访问对象 ID。
您可以使用displayWith
<input clrInput [(ngModel)]="order.customer" name="customer [matAutocomplete]="customerAutoComplete"/>
<mat-autocomplete #customerAutoComplete="matAutocomplete" (optionSelected)="onSelectCustomer($event)" [displayWith]="displayProperty">
<mat-option *ngFor="let customer of customerList" [value]="customer">
{{customer.customName}}
</mat-option>
</mat-autocomplete>
在component.ts
public displayProperty(value) {
if (value) {
return value.customName;
}
}
我使用反应形式,并且在分配值时像你一样,因为当我加载 api 数据时它不会 select 它。
我有一个简单的用例,我在其中循环对象数组。
我想将 属性 "customName" 显示到输入字段,但也能够为 http 调用检索其 ID 值。
<input clrInput [(ngModel)]="order.customer" name="customer [matAutocomplete]="customerAutoComplete"/>
<mat-autocomplete #customerAutoComplete="matAutocomplete" (optionSelected)="onSelectCustomer($event)">
<mat-option *ngFor="let customer of customerList" [value]="customer">
{{customer.customName}}
</mat-option>
</mat-autocomplete>
当我将对象绑定到值时,我可以使用 optionSelected 检索整个对象。但是输入会按预期显示[Object object]。
当我将 customer.customName 绑定到值时,我得到了显示的字符串,但无法访问对象 ID。
您可以使用displayWith
<input clrInput [(ngModel)]="order.customer" name="customer [matAutocomplete]="customerAutoComplete"/>
<mat-autocomplete #customerAutoComplete="matAutocomplete" (optionSelected)="onSelectCustomer($event)" [displayWith]="displayProperty">
<mat-option *ngFor="let customer of customerList" [value]="customer">
{{customer.customName}}
</mat-option>
</mat-autocomplete>
在component.ts
public displayProperty(value) {
if (value) {
return value.customName;
}
}
我使用反应形式,并且在分配值时像你一样,因为当我加载 api 数据时它不会 select 它。