如何向 angular 中的 table 添加行?
how to add rows to a table in angular?
我有这个 table,它使用 JSON 文件中的数据,我如何添加允许用户在文本字段中输入数据并将该数据添加到 table?
这是我所拥有内容的简单预览,它将 JSON 中的数据显示在 table
中
<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 文件(我知道这是不可能的),只是 table
您只需添加按钮单击处理程序 addHandler()
,然后它将在数组 employee
中插入新元素,并将该数组简单地绑定到您的 table。因此,每次您在输入字段中使用新数据按下添加按钮时,新条目都会添加到您的 table employee
.
.ts file
name = '';
id = '';
job = '';
employee = [];
addHandler(){
this.employee.push({
empName:this.name,
empId:this.id,
empJob:this.job
})
}
.html file
<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>
工作演示:link
我有这个 table,它使用 JSON 文件中的数据,我如何添加允许用户在文本字段中输入数据并将该数据添加到 table?
这是我所拥有内容的简单预览,它将 JSON 中的数据显示在 table
中<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 文件(我知道这是不可能的),只是 table
您只需添加按钮单击处理程序 addHandler()
,然后它将在数组 employee
中插入新元素,并将该数组简单地绑定到您的 table。因此,每次您在输入字段中使用新数据按下添加按钮时,新条目都会添加到您的 table employee
.
.ts file
name = '';
id = '';
job = '';
employee = [];
addHandler(){
this.employee.push({
empName:this.name,
empId:this.id,
empJob:this.job
})
}
.html file
<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>
工作演示:link