【问题标题】:angular material autocomplete - how to display a specified property of selected object角度材料自动完成 - 如何显示选定对象的指定属性
【发布时间】:2021-10-13 07:22:28
【问题描述】:

我有一个简单的用例,我在其中循环一个对象数组。

我想在输入字段中显示属性“customName”,但也能够检索其 id 值以进行 http 调用。

<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 绑定到 value 时,我会显示字符串,但无法访问对象 id。

【问题讨论】:

    标签: angular autocomplete angular-material


    【解决方案1】:

    您可以使用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;
        }
      }
    

    【讨论】:

    • 非常感谢!一定是在文档中错过了
    【解决方案2】:

    我使用响应式表单,并且在分配值时像您一样,因为在我加载 api 数据时它没有选择它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 2020-10-26
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多