Rendering incremental updates with *ngFor?

谁说胖子不能爱 提交于 2019-12-23 06:28:32

问题


If we have an Observable<Todo[]>, as shown below, is it possible to provide the template with delta updates? For example if the Observable<Todo[]> is getting values from a BehaviorSubject's next() call, could that broadcast incremental changes. My current understanding is that it has to broadcast the entire new array, but figured I'd check see if anything in this space is available?

 template: '<todo *ngFor="let todo of todos$ | async" [todo]="todo"><todo>'

Background

I'm attempting to design an Entity store that is reactive and clients can subscribe to streaming feeds of the store. So for example we could do:

const todoStore = new Store<Todo>();
const all:Observable<Todo[]> = todoStore.selectAll();

or

const add:Observable<Todo[]> = todoStore.selectAdd();

So if we can do incremental updates with the template rendering then the BehaviorSubject<Todo> only needs to broadcast the next Todo instance that was just added, allowing greater efficiency.

All of the instances are tracked by assigning a UUID that is keyed by a symbol const ID = Symbol('GUID'). todo[ID] = uuid().


回答1:


When rendering lists, generally using *ngFor, you can use trackBy. It helps Angular understand and track which element was added or removed from the list with the help of a unique identifier for it.

Now, whenever the list changes, Angular will track which item(s) were added or removed and create or destroy only the items that changed.

Here's how you can implement it

In your Template:

<todo 
  *ngFor="let todo of todos$ | async;trackBy: trackByFunction" 
  [todo]="todo">
<todo>

In your TypeScript Class:

trackByFunction(index, item) {
  return item.uniqueIdentifier || index;
}

A better way would be to return an id or a unique identifier on the item if there is.



来源:https://stackoverflow.com/questions/52133889/rendering-incremental-updates-with-ngfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!