[英]ngFor trackBy stil re-rendering DOM?
I activated trackBy in my ngFor and i confirmed that it is called and working, but I still notice the DOM is re-rendered in my browser which cause the rows to flicker. 我在ngFor中激活trackBy,并确认它已被调用并且可以正常工作,但是我仍然注意到DOM在我的浏览器中重新渲染,这导致行闪烁。 What is happening here?
这是怎么回事 In Angular1 I can see in my browser/chrome debugger that the DOM isn't updated/replaced when using track by item.id and no flicker occurs, why isn't this the case in angular2.
在Angular1中,我可以在浏览器/ chrome调试器中看到在使用track by item.id时未更新/替换DOM,并且没有闪烁,为什么在angular2中不是这种情况。 Is there some error in my code or does stuff happen under the hood that I am not aware off actually doing something good?
我的代码中是否存在某些错误,或者在我不知道实际上做得很好的情况下发生了某些事情?
<tr *ngFor="let item of items| async; trackBy:itemTrackBy">
itemTrackBy(index: number, item: MyItem) {
return item.id;
}
EDIT I tracked the error to be in the observable in my API service causing this, but still don't know why. 编辑我跟踪到我的API服务中的可观察到的错误导致此问题,但仍然不知道为什么。
this.items= this.apiService.getItems(searchText).share();
getItems(search?: string): Observable<Item[]> {
let searchParams = new URLSearchParams();
if (search) {
searchParams.set('searchText', search);
}
return this.http
.get(API_BASE_URL + '/items', {search: searchParams})
.map(response => response.json())
.catch(this.handleError);
}
Solution 解
Solved with using the same observable this.items instead of replacing it with a new one each time I reload new data. 使用相同的可观察this.items解决,而不是每次我重新加载新数据时都用一个新的替代。
this.items = Observable.concat(Observable.of(''), this.searchInput.valueChanges)
.debounceTime(200)
.map((value:string) => value.trim())
.distinctUntilChanged()
.switchMap(search => this.apiService.getItems(searchText);
I'm not sure how you implement the change function but I have implemented this code and it works fine: 我不确定如何实现更改功能,但是我已经实现了以下代码,并且可以正常工作:
export class AppComponent {
episodes = Observable.of([
{ title: 'Winter Is Coming', id: 0 }
]);
add() {
this.episodes = Observable.of([
{ title: 'Winter Is Coming', id: 0 },
{ title: 'The Kingsroad', id: 1 }
])
}
itemTrackBy(index: number, item) {
return item.id;
}
}
<button (click)="add()">Add</button>
<ul>
<li *ngFor="let episode of episodes | async; trackBy: itemTrackBy">
{{episode.title}}
</li>
</ul>
When you click on the add button you will see in the devtools -> inspect element only the added item flicker. 单击添加按钮时,您将在devtools-> inspect元素中仅看到添加的项目闪烁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.