[英]delete particular row in a table
i just started with angular.i checked few links stackoverflow links but none worked in my case.i have table where i am adding rows dynamically and i also need to delete rows dynamically but my code deleting rows from the last row even i am clicking delete button of some other row.i used below code and i am giving stackblitz link below.我刚开始使用 angular。我检查了几个链接 stackoverflow 链接,但在我的情况下没有任何工作。我有一个表,我正在动态添加行,我还需要动态删除行,但我的代码删除了最后一行的行,即使我点击删除一些其他行的按钮。我在下面的代码中使用,我在下面给出了 stackblitz 链接。 thanks in advance.
提前致谢。
rows = [1]; addrows() { this.rows.push(1); } deleterow(row){ this.rows.splice(row, 1); }
<table> <tr *ngFor="let row of rows;"> <td> something</td> <td> something</td> <td> something</td> <td> <button class="btn btn-danger" (click)="deleterow(i)">Delete</button> </td> <tr> <table> <div class="text-center"> <button class="btn btn-primary" (click)="addrows()">ADD more rows</button> </div>
You need to use the row's index to splice the row.您需要使用行的索引来拼接行。 You are currently just hoping that a variable
i
gets magically created.您目前只是希望神奇地创建一个变量
i
。
In my solution's component.ts, I am going to allow my HTML to add to and delete from a simple array.在我的解决方案的 component.ts 中,我将允许我的 HTML 向一个简单数组添加和删除。
component.ts组件.ts
counter: number = 0;
rows = [];
addRow() {
this.counter++;
this.rows.push(this.counter);
}
deleteRow(row: number) {
this.rows.splice(row, 1);
}
The key to the deleteRow
function is that you need access to the current index within *ngFor
. deleteRow
函数的关键是您需要访问*ngFor
的当前索引。 For that, you can use let i = index
within the *ngFor
to store the current index in a variable i
.为此,您可以在
*ngFor
使用let i = index
将当前索引存储在变量i
。
component.html组件.html
<table>
<tr *ngFor="let row of rows; let i = index">
<td>{{row}}</td>
<td><button (click)="deleteRow(i)">Delete row</button></td>
</tr>
</table>
<button (click)="addRow()">Add row</button>
DEMO: https://stackblitz.com/edit/angular-7uwuye演示: https : //stackblitz.com/edit/angular-7uwuye
Javascript Javascript
deleterow(id){ document.getElementById("row"+id).remove(); }
HTML HTML
<td id="row1"> <button class="btn btn-danger" onclick="deleterow(1)">Delete</button> </td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.