【发布时间】:2019-10-28 11:01:23
【问题描述】:
我想将ngFor 与async 数据(从API 加载)和trackBy 一起使用以提高性能并更新列表,而不会在数据更新时出现DOM 闪烁/闪烁。
如果数据是静态的 - 一切正常。但是当我尝试使用从 API 加载的数据时 - trackBy 不起作用。
直播
来自 API:https://stackblitz.com/edit/angular-hx4p39
静态数据:https://stackblitz.com/edit/angular-myb6vj
组件
export class AppComponent {
constructor(private http: HttpClient){}
comments$: Observable<Comment[]> = this.http.get<Comment[]>(`https://jsonplaceholder.typicode.com/comments?_start=0&_limit=5`);
add() {
this.comments$ = this.http.get<Comment[]>(`https://jsonplaceholder.typicode.com/comments?_start=0&_limit=6`);
}
edit() {
this.comments$ = this.comments$.pipe(
map(comments => {
comments.map( comment => {
if(comment.id === 5){ comment.name = 'edit'; }
return comment;
});
return comments;
})
);
}
itemTrackBy(index: number, item: Comment) {
return item.id;
}
}
interface Comment {
postId;
id;
email;
name;
body;
}
模板
<button (click)="add()">Make 6</button>
OR
<button (click)="edit()">edit 5-th element</button>
<ul>
<li *ngFor="let comment of (comments$ | async); trackBy: itemTrackBy">
{{comment.id}} - {{comment.name}}
</li>
</ul>
【问题讨论】:
标签: javascript angular rxjs ngfor