Angular 2 – 根据其中一个属性从对象数组中删除元素
发布时间:2020-12-17 17:56:50 所属栏目:安全 来源:网络整理
导读:我正在尝试根据Angular 2中的一个属性从对象数组中删除一个元素. 如何实现removeItem函数,以便根据其id属性从数组中删除注释对象,从而将其从列表中删除? 这是HTML模板(所有注释都包含ngFor循环): div *ngFor="let comment of list" button (click)="remove
我正在尝试根据Angular 2中的一个属性从对象数组中删除一个元素.
如何实现removeItem函数,以便根据其id属性从数组中删除注释对象,从而将其从列表中删除? 这是HTML模板(所有注释都包含ngFor循环): <div *ngFor="let comment of list"> <button (click)="removeItem({{comment.id}})">delete</button> (... comment.... ) .... 这里是Angular 2代码: export class Comments { list = [new Comment(1,"text one","koby",new Date("2015.01.02")),new Comment(2,"text two","adim",new Date("2017.02.02")),new Comment(6,"text six","asaf",new Date("2016.11.04")) ]; addItem(val: string) { this.list.push(new Comment(3,"kokoko","kobydo",new Date("2015.01.02"))); } removeItem(id: number) { // How do I remove it from the array ? } } export class Comment { constructor( public id: number,public text: string,public creator: string,public date: Date ) { } } 解决方法
你可以.filter()它:
removeItem(id: int) { this.list = this.list.filter(item => item.id !== id); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |