在使用trackBy进行轮询时,强制刷新组件的视图。可以通过触发CD检测 (ChangeDetectorRef.detectChanges()
)或者强制刷新 (this.ngZone.run(() => {})
)来实现。以下是示例代码:
@Component({
selector: 'my-component',
template: `
- {{ item }}
`
})
export class MyComponent implements OnInit, OnDestroy {
items: string[] = [];
private subscription: Subscription;
constructor(private myService: MyService, private cd: ChangeDetectorRef, private ngZone: NgZone) {}
ngOnInit() {
this.subscription = timer(0, 1000).subscribe(() => {
this.myService.getItems().subscribe(items => {
this.items = items;
// 触发CD检测
this.cd.detectChanges();
// 或者强制刷新
this.ngZone.run(() => { });
});
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
trackByFn(index: number, item: string) {
return item;
}
}