首页 > 解决方案 > 每次 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但我很难在我的代码上设置它。

标签: javascriptangularngfor

解决方案


尝试使用ChangeDetectionStrategy.OnPushlast的变量ngFor。因为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();

推荐阅读