javascript - 每当 ngFor 完成显示数据时执行一个函数

标签 javascript angular ngfor

每次我的 ngFor 完成从 API 加载数据时,我都会尝试调用一个函数。

但回调仅在首次加载 ngFor 时触发。

如何在每次 ngFor 更改时执行回调;

我使用了这个答案:https://stackoverflow.com/a/38214091/6647448

这是我到目前为止所拥有的......

HTML

<button class="btn" (click)="changeDate()"></button>

<div *ngFor="item of items; let last = last">
    <div>{{item}}{{last ? ngForAfterInit() : ''}}</div>
</div>

TS

this.ngForIsFinished = true;

ngForAfterInit() {
    if (this.ngForIsFinished) {
        this.ngForIsFinished = false;
    }
}

changeDate() {
    // this is where i trigger my ngFor to change its content
}

回答者说您只需将 ngForIsFinished 设置回 true 但我很难在我的代码中设置它。

最佳答案

尝试使用ChangeDetectionStrategy.OnPushngForlast变量。因为 ChangeDetectionStrategy.Default 总是检查方法,所以 fooMethod(...) 将被调用多个项目:

<div *ngFor = "let title of iterated; let i=index; let last=last">
  {{last ? fooMethod(last) : '' }}  
</div>

你的组件.ts:

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent  {
  name = 'Angular 4';

  iteratedData = [
      {"title":"test1","description":"foo","name":"name1"}, 
      {"title":"test2","description":"foo","name":"name2"}, 
      {"title":"test3","description":"foo","name":"name3"}, 
      {"title":"test4","description":"foo","name":"name4"}
  ];

  fooMethod(v) {
    if (v)
      console.log(`This is from the method ${v}`);
  }
}

更新:

加载数据后,您应该调用 slice 方法,因为 Angular 2 更改检测策略不会检查数组或对象的内容。因此尝试在突变后创建数组的副本:

this.iteratedData.push(newItem);
this.iteratedData = this.iteratedData.slice();

或者:

constructor(private changeDetectorRef: ChangeDetectorRef)

并且您可以调用方法markForCheck来触发changeDetection:

this.iteratedData.push(newItem);
this.changeDetectorRef.markForCheck();

关于javascript - 每当 ngFor 完成显示数据时执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58216198/

相关文章:

javascript - 如何使用 ng2-izitoast 将自定义 CSS 应用于 Toast?

javascript - Angular 垫菜单

使用 *ngFor 缺少数组中的 Angular 2 第一项

Angular2 我可以得到 ngFor 的计数吗?

javascript - 如何更改按钮的大小并为其添加背景颜色?

javascript - 在表单上使用 jquery show() 和 hide()

javascript - 使用 Angular Material 上传文件

javascript - 如何将缺失的对象添加到数组中?

Angular ng用于迭代多个 HTML 项目

html - 如何使用 *ngFor 显示数据