Han*_*Che 1 autocomplete angular-material angular
我有一个简单的用例,我循环遍历对象数组。
我想在输入字段中显示属性“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>
Run Code Online (Sandbox Code Playgroud)
当我将对象绑定到值时,我可以使用 optionSelected 检索整个对象。但是输入将按预期显示 [Object object]。
当我将 customer.customName 绑定到 value 时,我会显示字符串,但没有任何访问对象 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>
Run Code Online (Sandbox Code Playgroud)
在 component.ts
public displayProperty(value) {
if (value) {
return value.customName;
}
}
Run Code Online (Sandbox Code Playgroud)