我对javascript和打字稿类型的东西很新。我正在研究一个离子应用程序,它从数据库中读取值列表。然后它将它们存储在一个数组中,并循环遍历每个元素,从而创建一个离子项。对于每个项目,都会创建一个删除按钮。我想这样做,以便当用户点击删除按钮时,它将从数组中删除存储在离子项中的值。一旦从数组中删除了值,我就可以更新数据库。
我最初尝试使用用于生成离子项的可迭代值,但这没有意义,因为它不再在范围内。我对如何将按钮所在元素的值传递给函数感到很遗憾。
<ion-list class = "list" *ngIf="isCommentToggle" >
<ion-item id = "comments" *ngFor="let item of streamComments">
{{item}}
<button *ngIf="item" color="danger" ion-button (click)="onDeleteComment()" {{item}}="deleteComment">Delete</button>
</ion-item>
</ion-list>
具有功能的打字稿文档
onDeleteComment(){
this.gaugeList.addCommentList(this.stream);
}
我只是想要一种方法来捕获存储在父元素中的变量,其中按钮被称为Here is the application view
尝试以下过程:
<ion-list class = "list" *ngIf="isCommentToggle" >
<ion-item id = "comments" *ngFor="let item of streamComments;let i=index">
{{item}}
<button *ngIf="item" color="danger" ion-button (click)="onDeleteComment(i)" {{item}}="deleteComment">Delete</button>
</ion-item>
</ion-list>
请注意,我添加了let i=index
,其中i
是每个元素的索引。现在你可以使用i
从数组中删除特定值,如下所示:
onDeleteComment(i:number){
this.streamComments.splice(i,1);
}
它从索引号为streamComments
的i
数组中删除了一个值。
希望它能帮到你!!!
您可以将元素传递给onDeleteComment()
函数:
<button *ngIf="item" color="danger" ion-button (click)="onDeleteComment(item)"
{{item}}="deleteComment">Delete</button>
然后在你的打字稿中:
onDeleteComment(item) {
// Do whatever you need to do with 'item'
this.gaugeList.addCommentList(this.stream);
}
或者,您也可以使用*ngFor="let item of streamComments; let i = index"
在循环上声明一个索引变量,并将其传递给onDeleteComment()
。然后:
onDeleteComment(index: number) {
// The item that called this function is this.streamComments[index]
this.gaugeList.addCommentList(this.stream);
}
Hello配合只是从数组中删除该项,然后将该数组发送回db。
<ion-list class = "list" *ngIf="isCommentToggle" >
<ion-item id = "comments" *ngFor="let item of streamComments">
{{item}}
<button *ngIf="item" color="danger" ion-button
(click)="onDeleteComment(item)"
{{item}}="deleteComment">Delete</button>
</ion-item>
</ion-list>
在你的Ts
onDeleteComment(item){
let targetIndex = this.gaugeList.findIndex(element => element === item);
this.gaugeList.splice(targetIndex, 1);
//Now send this.gaugeList to backend
}