我有一个简单的HTML表格,有三列:
<table >
<thead>
<tr>
<td class="tdBorderEmail"><label>Action</label></td>
<td class="tdBorderEmail"><label>First Name</label></td>
<td class="tdBorderEmail"><label>Last Name</label></td>
<td class="tdBorderEmail"><label>Email</label></td>
</tr>
</thead>
<tbody>
<tr *ngFor="let dynamic of dynamicArray; let i = index;">
<td (click)="deleteRow(i)">
<i class="fa fa-trash "></i>
</td>
<td>
<input style="width:120px" name="{{dynamic.firstName}}" [(ngModel)]="dynamic.firstName" type="text" />
</td>
<td>
<input style="width:120px" name="{{dynamic.lastName}}" [(ngModel)]="dynamic.lastName" type="text" />
</td>
<td>
<input style="width:250px" name="{{dynamic.emailAddress}}" [(ngModel)]="dynamic.emailAddress" type="email"/>
</td>
</tr>
<tr>
<td (click)="addRow()">
<i class="fa fa-plus "></i>
</td>
</tr>
</tbody>
</table>
打开时显示良好,我可以输入三个数据字段,并查看TS文件中的angular代码,我可以看到填充的值。然而,当我使用以下代码添加新行:
addRow() {
this.newDynamic = {firstName: "", lastName: "",emailAddress:""};
this.dynamicArray.push(this.newDynamic);
console.log('New row added successfully', 'New Row');
}
空白前面所有行的值。当我查看TS文件中的值时,它被正确填充。它只是不再显示在页面上。什么好主意吗?我尝试了许多其他方法,甚至在添加后添加了.slice(),但似乎没有任何帮助。
你的方法很好。唯一可以优化的是,
-
声明数组为空
动态数组= [];
-
将新行对象直接推送到数组
this.dynamicArray。push({firstName: "; lastName: "; emailAddress:"});
下面是工作示例,
https://stackblitz.com/edit/angular-ivy-6bt4hk?file=src/app/app.component.ts