angular - 如何以角度向表格添加行?
问题描述
我有这个使用 JSON 文件中的数据的表,如何添加一个允许用户在文本字段中输入数据并将该数据添加到表中的函数?
这是我所拥有的简单预览,它在表格中显示 JSON 中的数据
<table>
<th> Name </th>
<th> ID </th>
<th> Job </th>
<tr *ngFor="let emp of employe">
<td>{{emp.empName}}</td>
<td>{{emp.empId}}</td>
<td>{{emp.empJob}}</td>
</tr>
</table>
Name: <input type="text">
ID: <input type="text">
Job: <input type="text">
<button> Add </button>
注意:我不想添加到 JSON 文件(我知道这是不可能的),只是表格
解决方案
您只需添加按钮单击处理程序addHandler()
,然后该处理程序将在数组中插入新元素employee
并将此数组绑定到您的表。因此,每次您在输入字段中按下带有新数据的添加按钮时,都会将新条目添加到您的表中employee
。
.ts 文件
name = '';
id = '';
job = '';
employee = [];
addHandler(){
this.employee.push({
empName:this.name,
empId:this.id,
empJob:this.job
})
}
.html 文件
<table>
<th> Name </th>
<th> ID </th>
<th> Job </th>
<tr *ngFor="let emp of employee">
<td>{{emp.empName}}</td>
<td>{{emp.empId}}</td>
<td>{{emp.empJob}}</td>
</tr>
</table>
<br><br>
Name: <input type="text" [(ngModel)]="name"><br>
ID: <input type="text" [(ngModel)]="id"><br>
Job: <input type="text" [(ngModel)]="job"><br>
<button (click)="addHandler()"> Add </button>
工作演示:链接
推荐阅读
- networking - 如何使用 UdpSocket 使用特定的网络接口进行发送?
- ajax - Laravel - 每个论坛获得第一个线程 all() 结果
- php - 使用贝宝沙箱卷曲授权
- android - 在 android 和 iOS 移动应用中遇到无效输入错误消息
- c# - Unity LogitechSDK 无法检测到我的 G29 方向盘
- c# - 为什么我的用户控件绘制事件仅在一个控件上填充我的矩形?
- ios - CAGradientLayer 不填充宽度
- python - 在 Pyspark Worker 上加载文件一次
- python - Python列出本地网络上的所有设备,以及IP地址
- python - 从 Python 中的 HTML 链接下载文本数据