使用* ngFor渲染增量更新? [英] Rendering incremental updates with *ngFor?

查看:76
本文介绍了使用* ngFor渲染增量更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个Observable<Todo[]>,如下所示,是否可以为模板提供增量更新?例如,如果Observable<Todo[]>BehaviorSubjectnext()调用中获取值,则可以广播增量更改.我目前的理解是,它必须广播整个新阵列,但是我想检查一下该空间中是否有可用空间?

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>'

背景

我正在尝试设计一个反应性的Entity商店,客户可以订阅该商店的流提要.例如,我们可以这样做:

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();

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

因此,如果我们可以使用模板渲染进行增量更新,则BehaviorSubject<Todo>仅需要广播刚刚添加的下一个Todo实例,从而提高效率.

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.

通过分配由符号const ID = Symbol('GUID')键控的UUID来跟踪所有实例. todo[ID] = uuid().

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

推荐答案

呈现列表时,通常使用*ngFor,可以使用trackBy.借助它的唯一标识符,它可以帮助Angular了解和跟踪从列表中添加或删除了哪个元素.

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.

现在,只要列表更改,Angular就会跟踪添加或删除的项目,并仅创建或销毁更改的项目.

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

这是实现它的方式

在您的模板中:

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

在您的TypeScript类中:

In your TypeScript Class:

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

更好的方法是在item上返回ID或唯一标识符.

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

这篇关于使用* ngFor渲染增量更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆