【问题标题】:Angular - invoke function on last element in *ngForAngular - 在 *ngFor 中的最后一个元素上调用函数
【发布时间】:2019-05-16 22:58:29
【问题描述】:

如何在 *ngFor 迭代器的最后一个元素处调用函数。下面是我尝试过的代码,但它调用了无限次。有没有办法在最后一个元素调用函数?

感谢您的帮助

模板.html

<div class="some-class" *ngFor="let item of items index as i; last as isLast">
   <div *ngIf="isLast">{{callSomeFunc(isLast)}}</div>
</div>

组件.ts

callSomeFunc(isLast) {
  console.log(isLast)
}

【问题讨论】:

  • 您的代码按预期工作,返回 true 两次不是无限的。您是否在项目上提供了正确的数组?
  • 添加 ngIf="i==isLast" 检查索引是否在最后位置
  • @Gokul,i 是索引,它是一个数字。 isLast 是一个布尔值
  • 使用 *ngIf="isLast" 在 *ngFor 中调用函数是您能想到的最糟糕的想法:*ngFor 在应用程序的生命周期中被评估多次。为什么在获取“items”的值时不调用该函数?

标签: javascript angular ngfor


【解决方案1】:

您在*ngFor 中漏掉了分号。

解决方案:

<div class="some-class" *ngFor="let item of items; index as i; last as isLast">
  <div *ngIf="isLast">{{callSomeFunc(isLast)}}</div>
</div>

【讨论】:

  • 每次@Saddam 都会调用,我只需要调用一次函数。
【解决方案2】:

补充我的评论 如果你有一个像

这样的组件
<div class="some-class" *ngFor="let item of [0,1,2];let i=index;let isLast=last">
   <div *ngIf="isLast">{{callSomeFunc(i)}}</div>
</div>

//In ts

callSomeFunc(value:any){
    console.log(value)  //You'll see in console severals 2
  }

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 2021-02-28
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多