首页 > 解决方案 > 在 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,而不仅仅是其自身数组中的对象值。

提前致谢。

标签: angularmaterial-ui

解决方案


您可以向项目(选定的)添加一个新属性并在 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}}

推荐阅读