Angular用户新增表单如何实现点击删除按钮删除对应用户,可否传递用户索引
实现方案
完全可以通过传递用户索引实现删除功能,也可以选择传递用户唯一id实现,两种方案具体实现如下:
方案1:传递索引实现(适合列表无排序/筛选/分页的简单场景)
第一步:修改子组件TableComponent,新增输出事件
修改table.component.ts,新增删除事件向外传递索引:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { User } from '../interfaces/user.model'; // 导入用户接口替换any,规范类型 @Component({ *** }) export class TableComponent implements OnInit { @Input() users: User[]; @Output() deleteUser = new EventEmitter<number>(); // 定义输出事件,参数为用户索引 constructor() { } ngOnInit(): void { } // 触发删除事件 onDelete(index: number) { this.deleteUser.emit(index); } }
第二步:修改子组件模板,绑定索引和点击事件
修改table.component.html,在遍历的时候获取索引,绑定删除按钮的点击事件:
<table class="ui celled table"> <thead> *** </thead> <tbody> <!-- 新增let i = index获取当前遍历项的索引 --> <tr *ngFor="let user of users; let i = index"> <td>{{user.id}}</td> <td>{{user.firstName}}</td> <td>{{user.lastName}}</td> <td>{{user.eMail}}</td> <td style="width: 40px;" > <button class="delButton" (click)="onDelete(i)"> <i class="times icon"></i> </button> </td> </tr> </tbody> </table>
第三步:修改父组件FormComponent,实现删除逻辑
首先在form.component.ts中新增删除方法:
import { Component, OnInit } from '@angular/core'; import { User } from '../interfaces/user.model'; @Component({ *** }) export class FormComponent implements OnInit { idNumber: number = 0; userInfo: User[] = []; constructor() { } addUser(firstname: HTMLInputElement, lastname: HTMLInputElement, email: HTMLInputElement) { this.idNumber += 1; this.userInfo.push({ id: this.idNumber, firstName: firstname.value, lastName: lastname.value, eMail: email.value }); console.log(this.userInfo) *** } // 新增删除方法:根据索引删除数组元素 deleteUserByIndex(index: number) { this.userInfo.splice(index, 1); } ngOnInit(): void { } }
然后找到父组件模板中引用TableComponent的位置,绑定子组件抛出的删除事件:
<!-- 父组件模板中引用子组件的代码 --> <app-table [users]="userInfo" (deleteUser)="deleteUserByIndex($event)"></app-table>
方案2:传递用户ID实现(更稳妥,适合所有场景)
如果你的列表会有排序、筛选、分页这类操作,索引可能和原数组位置不匹配,用用户唯一ID删除更稳妥,修改点如下:
- 子组件
table.component.ts的触发方法改为传递用户ID:
onDelete(userId: number) { this.deleteUser.emit(userId); }
- 子组件模板绑定点击事件时传递用户ID:
<button class="delButton" (click)="onDelete(user.id)">
- 父组件
form.component.ts的删除方法改为按ID过滤数组:
deleteUserById(userId: number) { this.userInfo = this.userInfo.filter(user => user.id !== userId); }
- 父组件绑定事件时对应调整方法名即可:
<app-table [users]="userInfo" (deleteUser)="deleteUserById($event)"></app-table>
内容的提问来源于stack exchange,提问作者vaxo0012
相关产品推荐
相关产品推荐

