【发布时间】: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