每次我的 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
和ngFor
的last
变量。因为 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/