[英]Angular - Can't bind to 'ngValue' since it isn't a known property of 'mat-option'
I'm using angular 5 and I'm getting the console error:我正在使用 angular 5,但出现控制台错误:
Can't bind to 'ngValue' since it isn't a known property of 'mat-option'
无法绑定到“ngValue”,因为它不是“mat-option”的已知属性
My template looks something like as follows:我的模板如下所示:
<mat-select placeholder="Select Book" name="patient" [(ngModel)]="selectedBook">
<mat-option *ngFor="let eachBook of books" [ngValue]="eachBook">{{eachBook.name}}</mat-option>
</mat-select>
I've imported both MatSelectModule
and MatOptionModule
.我已经导入了
MatSelectModule
和MatOptionModule
。
How can we resolve this?我们如何解决这个问题?
The accepted answer is not a solution but a work-around, as value
and [ngValue]
serve different purposes.接受的答案不是解决方案,而是一种变通方法,因为
value
和[ngValue]
用于不同的目的。 value
can be used for simple string values, whereas [ngValue]
is necessary to support non-string values. value
可用于简单的字符串值,而[ngValue]
是支持非字符串值所必需的。
Per the documentation:根据文档:
If you have imported the FormsModule or the ReactiveFormsModule, this value accessor will be active on any select control that has a form directive.
如果您已导入 FormsModule 或 ReactiveFormsModule,则此值访问器将在任何具有表单指令的选择控件上处于活动状态。 You do not need to add a special selector to activate it.
您不需要添加特殊的选择器来激活它。
If you are getting this error, you most likely need to import either FormsModule
or ReactiveFormsModule
into your app.如果您收到此错误,您很可能需要将
FormsModule
或ReactiveFormsModule
导入您的应用程序。
For example, in app.module.ts
:例如,在
app.module.ts
:
import { FormsModule } from '@angular/forms';
// ...
imports: [
FormsModule,
...
]
你应该使用价值
[value]="eachBook"
I have met the same issue.我遇到了同样的问题。 The solution for me is to import 'ReactiveFormsModule'.
我的解决方案是导入“ReactiveFormsModule”。 So you can use
[ngValue]
to bind an object.所以你可以使用
[ngValue]
来绑定一个对象。
for mat-autocomplete, to use items instead of strings, for mat-option, ngValue wasn't available, however with [value], we can access the object by using option.value instead of option.viewValue:对于 mat-autocomplete,使用项目而不是字符串,对于 mat-option,ngValue 不可用,但是对于 [value],我们可以通过使用 option.value 而不是 option.viewValue 来访问对象:
allFruits: Item[] = [
{
name: 'hello',
selected: true,
},
{
name: 'world',
selected: false,
}
];
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
{{fruit.name}} {{fruit.selected}}
</mat-option>
</mat-autocomplete>
selected(event: MatAutocompleteSelectedEvent): void {
console.log('selected ', event.option.value); <----- THIS
console.log('selected ', event.option.viewValue); <---- NOT THIS
}
with option.value you get the object.使用 option.value 你得到对象。 With option.viewValue you will get a string representation of the innerHTML that the user sees.
使用 option.viewValue 您将获得用户看到的 innerHTML 的字符串表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.