在HTML中,未显示ngModel
已分配selectedValueModel的位置。
也尝试过[ngValue]
,并将undefined
赋予我的ngModelChange
函数。
谢谢。
foods: Food[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
selectedValueModel = {value: 'steak-0', viewValue: 'Steak'};
@Output() selectedValueChange = new EventEmitter()
changing(newValue: any) {
this.selectedValueModel = newValue
this.selectedValueChange.emit(newValue)
}
<mat-form-field>
<mat-select placeholder="Favorite food"
[(ngModel)]="selectedValueModel.value"
(ngModelChange)="changing($event)" name="food">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
答案 0 :(得分:1)
更改:
<mat-form-field>
<mat-select placeholder="Favorite food"
[(ngModel)]="selectedValueModel.value"
(ngModelChange)="changing($event)" name="food">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
收件人:
<mat-form-field>
<mat-select placeholder="Favorite food"
[(ngModel)]="selectedValueModel"
(ngModelChange)="changing($event)" name="food">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
答案 1 :(得分:1)
对于那些可能会因为 ngModel
未显示其模型值而遇到问题的人,您的表单中可能还有另一个具有相同 name
的输入。即
<form>
<input [(ngModel)]="selectedValueModel.value" name="food">
<input [(ngModel)]="anotherModel" name="food">
</form>
答案 2 :(得分:0)
与纯角度相反,要用Angular材质捕获整个对象,可以使用[value]
而不是[ngValue]
来绑定整个对象。
此外,既然我们要绑定整个对象,而不是原始对象,我们需要将您的预定义对象与数组中的对象进行比较,因此可以使用Angular提供的compareWith
。因此,将代码更改为:
<mat-select placeholder="Favorite food" [(ngModel)]="selectedValueModel"
(ngModelChange)="changing($event)" name="food" [compareWith]="compFn">
<mat-option *ngFor="let food of foods" [value]="food"> <!-- Add food as value! -->
{{food.viewValue}}
</mat-option>
</mat-select>
然后是compareWith:
compFn(c1: Food, c2: Food): boolean {
return c1 && c2 ? c1.value === c2.value : c1 === c2;
}
这里是 StackBlitz !