angular - 在 Angular 中将数组项绑定到 [(value)]
问题描述
嗨,我正在使用 Angular 材料,我有一个产品数组,可以在我的模板中创建一个表格
<tbody>
<tr *ngFor="let item of productArray | async; let i = index">
<th>
在这个循环中,我在标签上有另一个循环:
<th>
<mat-form-field>
<mat-select placeholder="Length" formControlName="lengthOption" [compareWith]="compareWith" [(value)]="item.lengthOption">
<mat-option *ngFor="let lengthOption of item.lengthOptions" [value]="lengthOption">
{{lengthOption.name}}
</mat-option>
</mat-select>
</mat-form-field>
我想利用[(value)]
.
我知道我可以设置[value]
为 lengthOption.name 例如,然后将绑定设置为[(Value)]="selected"
,然后我可以在我的组件中设置(selected = whatever)
它或通过在模板中查看它{{selected}}
。
我的查询是我可以从父数组中获取这个值,就像我在内部循环中尝试的那样:
*ngFor="let item of productArray | async; let i = index"
[(value)]="item.lengthOption"
productArray 上确实存在 lengthOption。
我想为每个产品 mat-select 设置一个初始选定值。
长度选项看起来像{ "id": 1, "name": "Ten Years" }
因此,我试图将对象设置为父数组中的 mat-option,而不仅仅是其自身数组中的对象值。
提前致谢。
解决方案
您可以向项目(选定的)添加一个新属性并在 ngModelChange 上更改它
<mat-select placeholder="Length" formControlName="lengthOption" (ngModelChange)="select($event, item)" [compareWith]="compareWith" [(value)]="item.lengthOption">
<mat-option *ngFor="let lengthOption of item.lengthOptions" [value]="lengthOption">
...
并尝试这样的事情来改变每次你选择一个新的:
select(selectedValue, item) {
item['selectedLengthOption'] = selectedValue;
}
您可以在循环内的模板中访问它
{{item.selectedLengthOption}}
推荐阅读
- python - 我不明白为什么当我通过 Anaconda navigator 安装它并看到它安装时,我得到 No module named 'pandas_datareader'?
- ios - Firebase getDocument(querySnapshot)不起作用
- xamarin - 如何在后面的代码中在 xamarin.forms shell 中添加两个页面
- arrays - 更改随机选择的图像的 Alpha 设置
- node.js - 如何直接调用亚马逊个性化服务?
- angular - 有没有办法在角度 ngModel 的 html 中设置对象的属性?
- javascript - ASP.Net Core C# 选择选项重定向更改选择的选项
- android - 只能将来自 firebase 的最后一个子子项显示到我的回收站视图(已更新)
- javascript - 解释为什么这个解决方案不会返回一个承诺?JS
- kubernetes - Kubectl 配置更改不会通过 Rancher CLI 保存