我有用户添加表单,每个用户都有删除按钮。我怎样才能让它删除它的用户?
Posted
技术标签:
【中文标题】我有用户添加表单,每个用户都有删除按钮。我怎样才能让它删除它的用户?【英文标题】:i have user adding form, each user has delete button. how can i make it delete it's user? 【发布时间】:2021-12-17 09:10:04 【问题描述】:user.model.ts // 用户接口
export interface User
id:number,
firstName:string,
lastName:string,
eMail:string
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)
***
ngOnInit(): void
table.component.ts
import Component, OnInit, Input from '@angular/core';
@Component(
***
)
export class TableComponent implements OnInit
@Input() users:any;
constructor()
ngOnInit(): void
table.component.html 我添加的每个用户都有一个删除按钮。我希望他们删除属于他们的用户。是否可以通过用户索引?
<table class="ui celled table">
<thead>
***
</thead>
<tbody>
<tr *ngFor="let user of users">
<td>user.id</td>
<td>user.firstName</td>
<td>user.lastName</td>
<td>user.eMail</td>
<td style="width: 40px;" ><button class="delButton"><i class="times icon"></i></button></td>
</tr>
</tbody>
</table>
【问题讨论】:
每个组件最好使用随机数。 【参考方案1】:试试下面的代码
<table class="ui celled table">
<thead>
***
</thead>
<tbody>
<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)="deleteUser(i)"><i class="times icon"></i></button></td>
</tr>
</tbody>
并且在table.component.ts文件里面添加如下函数
deleteUser(index: number) this.users.splice(index, 1);
【讨论】:
以上是关于我有用户添加表单,每个用户都有删除按钮。我怎样才能让它删除它的用户?的主要内容,如果未能解决你的问题,请参考以下文章