【问题标题】:How to get value stored inside parent element如何获取存储在父元素中的值
【发布时间】:2019-04-06 04:33:30
【问题描述】:

我对 javascript 和 typescript 类型的东西很陌生。我正在开发一个从数据库中读取值列表的离子应用程序。然后它将它们存储在一个数组中,并循环遍历每个元素,创建一个 ion-item。对于每个项目,都会创建一个删除按钮。我想要这样做,以便当用户单击删除按钮时,它将从数组中删除存储在 ion-item 中的值。从数组中删除值后,我可以更新数据库。

我最初尝试使用用于生成 ion-item 的可迭代值,但这没有意义,因为它不再在范围内。我对如何将按钮所在的元素的值传递给函数有点迷茫。

        <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

【问题讨论】:

  • 通过'用于生成离子项的可迭代值',您指的是item吗?

标签: javascript html angular ionic-framework


【解决方案1】:

尝试以下流程:

<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);
}

它从索引号istreamComments 数组中删除一个值。

希望对你有帮助!!!

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

您可以将元素传递给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);
}

【讨论】:

  • 感谢您的帮助!
【解决方案3】:

你好,伙计,只需从数组中删除项目,然后将数组发送回 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
  }

【讨论】:

  • 哇,这很简单!我不确定用于可迭代的变量是否仍会保留一个值,因为已经处理了 ngFor 循环。我试图通过将 {{item}} 中的值传递给 deleteComment 变量来完成这项工作。从那里我会找到存储在其中的键索引并将其从数组中删除。然而,这个解决方案效果更好。顺便说一下 .findIndex 方法不起作用。它告诉我该函数未在提供程序中定义,因此我选择使用 .indexOf 代替。
  • 我为错误的伙伴@scubasteve7 道歉,findIndex 只适用于回调。我将编辑我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 2014-11-05
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多