【发布时间】:2020-11-12 08:01:37
【问题描述】:
来自Angular的source code,下面的sn-p让我很困惑。
/**
* A function that defines how to track changes for items in the iterable.
*
* When items are added, moved, or removed in the iterable,
* the directive must re-render the appropriate DOM nodes.
* To minimize churn in the DOM, only nodes that have changed
* are re-rendered.
*
* By default, the change detector assumes that
* the object instance identifies the node in the iterable.
* When this function is supplied, the directive uses
* the result of calling this function to identify the item node,
* rather than the identity of the object itself.
*
* The function receives two inputs,
* the iteration index and the node object ID.
*/
@Input()
set ngForTrackBy(fn: TrackByFunction<T>) {
...
}
}
this._trackByFn = fn;
}
还有here 来自官方文档的一个示例,其中传递了trackBy 函数。
trackById(index: number, hero: Hero): number { return hero.id; }
源码说明
当提供此函数时,指令使用调用此函数的结果来标识项目节点,而不是对象本身的标识。
但是在上面的例子中,我们无论如何都传递了对象本身的身份(return hero.id;),但是通过一个附加函数。为什么我们需要那个?如果我们不传递任何这样的函数,Angular 不会按照文档默认执行它所做的事情,即获取对象本身的身份吗?
跟踪器函数的显式传递与 Angular 通常没有它时所做的有什么不同?
谢谢。
【问题讨论】:
标签: angular angular-directive ngfor