每当其集合更改时,TemplateRef项目都会被破坏 [英] TemplateRef items being destroyed every time their collection changes
问题描述
我在创建一个组件时遇到问题,该组件基于自定义 Observable
和自定义项 TemplateRef
呈现一组项.
该组件将 Observable
和 TemplateRef
用作输入,并适当地呈现它们.问题出在集合发生更改并且集合中的所有项目都被销毁并重新创建的地方.
当我依靠动画来指示项目进入和离开集合(或改变集合中的位置)时,这显然是有问题的.
如果我的组件是直接渲染组件(即不是 TemplateRef
输入),则不会出现每次更改集合时组件被销毁的问题.我想我可能已将问题范围缩小到了模板出口上下文中的 * ngFor
中的 item
.
我已经重现了这个问题
如上图所示,模板将被删除.
为避免这种情况,我建议您在 ngFor
上使用内置的 @Input()ngForTemplate
属性:
<代码>< div * ngFor =让项目项;模板:itemTemplate,trackBy:itemTrack"</div>
,对于您的 #feedItem
自定义模板,将 let-item
变量从以下位置更改:
< ng-template #feedItem let-item ="item">
收件人:
< ng-template #feedItem let-item ="$ implicit">
或简单地:
< ng-template #feedItem let-item>
另请参见
ngTemplateOutlet阻止指令正常工作
I'm having a problem creating a component that renders a a collection of items based on a custom Observable
and custom item TemplateRef
.
The component takes the Observable
and TemplateRef
as inputs and renders them appropriately. The problem comes in where the collection changes and all items in the collection are destroyed and recreated.
This is obviously problematic where I depend on animations to indicate items entering and leaving the collection (or changing position in the collection).
If my component, instead, renders the component directly (i.e. not the TemplateRef
input) I don't have this issue of components being destroyed every time the collection changes. I think I may have narrowed the problem down to passing the item
from the *ngFor
on the templates outlet context.
I've got a reproduction of the problem here demonstrating the difference between rendering the TemplateRef
and component directly. The ngOnDestroy
is logged to the console as well as an animation for when the component :enter
s. I think this plnkr demonstrates the problem clearly.
Any help with this would be appreciated.
I think I may have narrowed the problem down to passing the item from the *ngFor on the templates outlet context.
Yeah, that's because context
parameter always gets new object reference:
context: { index: index, item: item }
and therefore ngOnChange
hook will be called inside ngTemplateOutletDirective
:
as you can see in the picture above template will be removed.
To avoid it i would suggest you using built-in @Input() ngForTemplate
property on ngFor
:
<div *ngFor="let item of items; template: itemTemplate, trackBy: itemTrack"></div>
and for your #feedItem
custom template change let-item
variable from:
<ng-template #feedItem let-item="item">
to:
<ng-template #feedItem let-item="$implicit">
or simply:
<ng-template #feedItem let-item>
See also
这篇关于每当其集合更改时,TemplateRef项目都会被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!