因此,我正在使用Angular 5,我有两个数组,其中的数据是从数据库中提取的:
["Reports", "UI"]
和
0: {ranges: "Low", ph: 0, days: 0}
1: {ranges: "Mediu,", ph: 0, days: 0}
2: {ranges: "High", ph: 0, days: 0}
我在为第一个数组中的每个元素显示第二个数组。之后,我有一个输入,也像在第二个数组中那样重复输入
...
<tbody *ngFor="let i of paramsData; let y = index"> <---Repeat the data from first array
<ng-container *ngFor="let data of times; let x = index"> <---Repeat the data from second array in each element in the first array
<tr>
<td [attr.rowspan]="times.length" *ngIf="x == 0">{{i}}</td>
<td>{{data.ranges}}</td>
<td>
<input type="number" class="form-control" name='weight'>
</td>
<td>{{data.ph}}</td>
<td>{{data.days}}</td>
</tr>
</ng-container>
</tbody>
...
问题:如何获得由*ngFor
自动生成的输入中引入的值?我无法在formControlName
内分配值,因为所有输入将具有相同的名称,并且只会保存一个值。
此外,我不能使用[(ngModel)]="someArray[x]"
将值存储在数组中,因为它只会将第一次迭代的值保存在第二个ngFor
上。
我丢失了什么吗?有选择的办法吗?
-编辑-
链接到StackBlitz:https://stackblitz.com/edit/angular-ux4cqv
表格的屏幕截图
答案 0 :(得分:2)
您可以将表单实现为二维数组:
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormArray, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
formGroup: FormGroup;
params = ["Reports", "UI"];
ranges = [
{ranges: "Low", ph: 0, days: 0},
{ranges: "Medium,", ph: 0, days: 0},
{ranges: "High", ph: 0, days: 0}
]
constructor() {
var paramsArray = new FormArray([]);
this.params.forEach(t=> {
var rangeArray = new FormArray([]);
paramsArray.push(rangeArray);
this.ranges.forEach(t=> {
rangeArray.push(new FormControl(''))
});
});
this.formGroup = new FormGroup({
"values": paramsArray
});
}
}
app.component.html
<div [formGroup]="formGroup">
<table border="1" formArrayName="values">
<thead>
<tr>
<th>Param. de Estimación</th>
<th>Complejidad</th>
<th>Peso</th>
<th>Product. Hora</th>
<th>Esf. en Dias</th>
</tr>
</thead>
<tbody *ngFor="let i of params; index as y" [formArrayName]="y">
<ng-container *ngFor="let data of ranges; index as x">
<tr>
<td [attr.rowspan]="ranges.length" *ngIf="x == 0">{{i}}</td>
<td>{{data.ranges}}</td>
<td>
<input type="number" class="form-control" [formControlName]="x" placeholder="Weight" name='weight'>
</td>
<td>{{data.ph}}</td>
<td>{{data.days}}</td>
</tr>
</ng-container>
<button type="submit" *ngIf="y==1">Pto. de Referencia</button>
</tbody>
</table>
</div>
将表单值保存到“值”二维数组中,您可以通过调用formGroup.value
:
{
"values": [
[
"",
"",
""
],
[
"",
"",
""
]
]
}