我正在创建一个动态表,在click()上添加一行。但是,每次添加行都会重置上一行的值。
<tfoot>
<tr>
<td><button type="button" (click)="addRow()">Add row </td>
</tr>
</tfoot>
// html
<tbody>
<tr *ngFor="let row of rows">
<td><input name="something" type="text" [ngModel]="row.item.name </td>
</tr>
</tbody>
// component
...
this.item = {name: 'Superman'};
this.rows = [{
item: this.item
}];
....
this.addRow() {
this.rows.push({
item: this.item
});
}
答案 0 :(得分:0)
因为您多次在数组中推送相同的对象引用。因此,如果更改this.item
将有效地更改所有新添加的数组元素中的值(因为它们带有相同的对象引用)。
解决方案是,将clone对象推送到items数组。
this.rows.push({
item: Object.assign({}, this.item); //created clone
});
答案 1 :(得分:0)
[已解决]我们只需要使输入的名称唯一!
<tfoot>
<tr>
<td><button type="button" (click)="addRow()">Add row </td>
</tr>
</tfoot>
// html
<tbody>
<tr *ngFor="let row of rows; let i = index">
<td><input name="something_{{i}}" type="text" [ngModel]="row.item.name </td>
</tr>
</tbody>
// component
...
this.item = {name: 'Superman'};
this.rows = [{
item: this.item
}];
....
this.addRow() {
this.rows.push({
item: this.item
});
}