【问题标题】:Using ngValue with Angular Material autocomplete?将ngValue与Angular Material自动完成一起使用?
【发布时间】:2019-06-28 18:39:58
【问题描述】:

我传入一个对象作为我的值,需要使用 [ngValue] 而不是 [value]。

我的 HTML 如下所示:

<mat-input-container fxFlex="18" fxFlexOffset="1">
    <input
        matInput
        placeholder="Example"
        [matAutocomplete]="autocomplete"
        [ngModel]="user?.UserName"
        (ngModelChange)="filter($event)"
        [disabled]="disabled"/>
     <mat-autocomplete #autocomplete="matAutocomplete" 
                       (optionSelected)="optionSelected($event)" >
         <mat-option *ngFor="let selectedUser of availableUsers" [ngValue]="selectedUser">
             <span>{{ selectedUser?.UserName }}</span>
         </mat-option>
     </mat-autocomplete>
</mat-input-container>

作为演示,我也有一个堆栈闪电战,这里提供了我的错误: https://stackblitz.com/edit/angular-5wk4rl?file=app%2Fautocomplete-simple-example.html

我收到错误:

模板解析错误:

Can't bind to 'ngValue' since it isn't a known property of 'mat-option'.

1. If 'mat-option' is an Angular component and it has 'ngValue' input, then verify that 
   it is part of this module.
2. If 'mat-option' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the 
   '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the 
   '@NgModule.schemas' of this component.

正如堆栈上的其他答案所述,Angular - Can't bind to 'ngValue' since it isn't a known property of 'mat-option'

用户建议将其添加到模块文件中可以解决问题,但是当我尝试这样做时(如我在 stackblitz 中的 material-module.ts 中所见),错误仍然存​​在。

有什么建议吗?我将不胜感激!

【问题讨论】:

  • 您不能将 ngValue 属性绑定与 mat-option 一起使用,因为它只能与 option 元素一起使用。 mat-option 接受 [value] 绑定
  • 为什么要将对象作为自动完成选项值(而不是字符串)?
  • @ConnorsFan 因为有时数据模型使用对象而不是字符串。
  • @ConnorsFan 我已经更新了示例中的 html 以澄清

标签: html angular angular-material


【解决方案1】:
 <mat-option *ngFor="let option of options" [value]="option">

在此处查看文档:https://material.angular.io/components/autocomplete/overview

使用对象:

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
  <mat-option 
    *ngFor="let selectedUser of availableUsers" [value]="selectedUser">
      {{selectedUser.name}}
  </mat-option>
</mat-autocomplete>

在 xxx.ts 文件中:

displayFn(user?): string | undefined {
  return user ? user.name : undefined;
}

【讨论】:

  • 是的 - 这行得通。我想知道是否有办法让 [ngValue] 工作而不是 [value]。
  • 没有。为什么你认为你需要这样做?
  • 为什么需要使用[ngValue]?
  • 使用&lt;mat-autocomplete [displayWith]="displayFn" ...&gt;。见material.angular.io/components/autocomplete/…
  • @Jedo 我明白了,你可以使用 displayWith 。我更新了答案
猜你喜欢
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 2016-10-11
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多