angular删除数据有问题
angular制作一个删除按钮时不管点击哪个按钮,删除的都是表格的最后一个元素。数据是在一个数组里存储的。
app.component.ts:
这里传入的是数字,del中的Patient.indexOf是对象,找不到对象返回-1,再splice(-1,1)就是最后一个
<td> <button class="button" (click)="del(patient.Id)">Remove</button></td>
直接传入对象
<td> <button class="button" (click)="del(patient)">Remove</button></td>
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!【以下回答由 GPT 生成】
问题的关键在于如何通过点击按钮删除对应的表格元素。以下是解决该问题的一种方式:
首先,在app.component.ts
文件中,你需要创建一个存储表格数据的数组。这个数组可以在组件的构造函数中初始化,也可以直接声明在组件的类中。注意,实际的数据结构可能有所不同,取决于你的需求。
接着,在表格中渲染你的数据。使用*ngFor
指令来遍历数组,并为每个表格元素创建一个按钮。每个按钮都应该有一个点击事件处理函数,这个函数将删除对应的表格元素。
下面是具体的代码示例:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<table>
<thead>
<tr>
<th>名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of tableData; let i = index">
<td>{{ data.name }}</td>
<td><button (click)="deleteRow(i)">删除</button></td>
</tr>
</tbody>
</table>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
tableData = [
{ name: '数据1' },
{ name: '数据2' },
{ name: '数据3' }
];
deleteRow(index: number) {
this.tableData.splice(index, 1);
}
}
app.component.html:
<table>
<thead>
<tr>
<th>名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of tableData; let i = index">
<td>{{ data.name }}</td>
<td><button (click)="deleteRow(i)">删除</button></td>
</tr>
</tbody>
</table>
通过以上代码,在每行数据中的删除按钮上绑定了deleteRow()
方法,并且通过*ngFor
指令遍历了tableData
数组。当点击某个按钮时,会调用deleteRow()
方法并传入相应的索引值作为参数,然后使用splice()
方法从数组中删除对应的元素。
这样,点击每个按钮时就能够删除对应的表格元素了。
【相关推荐】