javascript - 每次 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.OnPush
和last
的变量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();
推荐阅读
- image - 如何获取在您管理的 Facebook 页面上发表评论的人的用户名和照片?
- java - Spring 5 反应式 websockets:客户端没有从热流中接收到相同的数据
- javascript - 尝试检索本地 json 文件时出现 ECONNREFUSED 错误
- typescript - 返回没有特定键的对象(动态,类型安全)
- angular - 如何将非VS项目部署到iis web deploy?
- python - 如何在同一数据上使用 Django for 循环两次
- python - 如何获得django最畅销的10款产品?
- php - 用jquery更改foreach中的变量名
- powershell - 吐出我们的随机命令问题的脚本 [Powershell]
- python - 如何在多个图表中绘制多列