Angular:在 ngFor 中获取当前索引

标签 angular

我有以下 Angular :

<div class="test" *ngFor="let item of data; let i = index">
    {{item}}
</div>

<div class="function_div" (click)="test(i);">Test Button </div>

然后在.ts中,

export class test{
   
  test(){
     console.log(i);
  }
  
}

我想获取一个带有当前索引号的变量。

我该怎么做才能获得当前索引?

谢谢

最佳答案

根据 OP 对问题的评论:

So, I am trying to get the index of the ngFor in order to do a comparison to array of data before triggering another function. For example, the test() function will be triggered when I click a button, then it will check the current index, and do something with it.

你应该这样做:

<div class="test" *ngFor="let item of data; let i = index">
    // In your case this line should be within ngFor loop
    <div class="function_div" (click)="test(i);">Test Button </div>
    {{item}}
</div>

Note : Never call function like :

{{ test(i) }} // this will be executed each time anything changes in loop

关于Angular:在 ngFor 中获取当前索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49123807/

相关文章:

javascript - Angular 可观察函数不返回所有响应

express - Angular 2 通用 Heroku 部署

Angular2 Http错误

javascript - Angular2 依赖项没有注入(inject)正确的路径

angularjs - 弹出的项目不能再使用构建命令

ASP.NET 核心 2 + Angular 4 : NodeInvocationException: Prerendering failed because of error: ReferenceError: window is not defined

angular - 始终显示日期选择器中的日历 - Angular

angular - Angular 5 中 Angular @angular/http URLSearchParams 类的替代品是什么

angular - 将模板作为内容传递,然后将其传递给另一个组件

javascript - Angular 5 + Popper.JS