首页 > 解决方案 > 如何以角度向表格添加行?

问题描述

我有这个使用 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 文件(我知道这是不可能的),只是表格

标签: angularangular7

解决方案


您只需添加按钮单击处理程序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>

工作演示:链接


推荐阅读