将数组项绑定到Angular中的[[value)]

时间:2018-07-03 13:03:15

标签: angular material-ui

嗨,我正在使用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"

lengthOption在productArray上确实存在。

这一点我想为每个垫选产品设置一个初始选择值。

lengthOption看起来像{ "id": 1, "name": "Ten Years" }

因此,我试图将对象设置为父数组的mat-option选项,而不仅仅是将其自身数组中的对象值设置为

谢谢。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:-1)

不建议使用动态名称进行双向绑定,并且它不能以预期的方式起作用。 将此[(value)]视为[(ngModel)]

您可以使用(onChange),或者如果您需要获取所有表单状态/信息,并且如果您的产品数组包含更多商品,请尝试使用formArray,它将使您的生活变得轻松。 https://angular.io/api/forms/FormArray

相关问题