admin管理员组文章数量:1357405
I am trying to create a list of items and delete them one by one. I have used (click)
and removeUser()
to delete the single item, unfortunately the output is that no matter what button is clicked, all the 3 items are deleted at the same time. Please help. Thank you
export class UserlistComponent {
users = [
{
id : '1',
name: 'Jack',
age: '33'
},
{
id : '2',
name: 'Kim',
age: '44'
},
{
id : '3',
name: 'Mag',
age: '22'
},
]
removeUser(id:string): void{
this.users = this.users.filter(user => user.id !== user.id)
}
}
<li *ngFor="let user of users">
{{user.name}} is {{user.age}} years old
<button (click)="removeUser(user.id)">Remove</button>
</li>
I am trying to create a list of items and delete them one by one. I have used (click)
and removeUser()
to delete the single item, unfortunately the output is that no matter what button is clicked, all the 3 items are deleted at the same time. Please help. Thank you
export class UserlistComponent {
users = [
{
id : '1',
name: 'Jack',
age: '33'
},
{
id : '2',
name: 'Kim',
age: '44'
},
{
id : '3',
name: 'Mag',
age: '22'
},
]
removeUser(id:string): void{
this.users = this.users.filter(user => user.id !== user.id)
}
}
<li *ngFor="let user of users">
{{user.name}} is {{user.age}} years old
<button (click)="removeUser(user.id)">Remove</button>
</li>
Share
Improve this question
edited Nov 27, 2021 at 7:28
Giannis
1,8401 gold badge13 silver badges33 bronze badges
asked Nov 26, 2021 at 9:34
lacertezzadellapenalacertezzadellapena
151 silver badge7 bronze badges
2 Answers
Reset to default 6You are using your filter on user.id
for both sides of the parison operator.
You need to pare with your method's parameter:
removeUser(id:string): void{
this.users = this.users.filter(user => user.id !== id)
}
Fix to your question
You are using the filter statement incorectly. You should use the parementer in removeUser
function to filter down the list.
removeUser(id:string): void{
this.users = this.users.filter(user => user.id !== id)
}
Better Approach
You could just splice the unwanted elements with Array.splice
Template
<li *ngFor="let user of users; let i = index">
{{user.name}} is {{user.age}} years old
<button (click)="removeUser(i)">Remove</button>
</li>
Component.ts
removeUser(index): void{
this.users.splice(index, 1)
}
本文标签: javascriptRemove an item from a list in AngularStack Overflow
版权声明:本文标题:javascript - Remove an item from a list in Angular - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744058145a2583630.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论