我正在传递一个对象作为我的值,并且需要使用[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中所看到的那样),错误仍然存在。
有什么建议吗?我将不胜感激!
答案 0 :(得分:2)
<mat-option *ngFor="let option of options" [value]="option">
在此处查看文档:{{3}}
要使用该对象:
<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;
}