这似乎有效。我正在尝试从容器中删除视图,但我需要要删除的视图的引用。
我学到了一些新东西
创建视图时,我们可以传递一个上下文对象。这就像传递给模板的数据(将其视为参数,模板是函数)。
let view:ViewRef = this.vc.createEmbeddedView(this.tmpl,
{option:{divId:'thumbnail-'+(this.divId++),
closeId:'close-'+(this.closeId++)
}} );
如果模板是
<ng-template #thumbnailTemplate let-option="option" let-index="index">
<div id="{{option.divId}}">
<img>
<a href="#" id="{{option.closeId}}" (click)="deleteIt(option)">template inserted at index {{option.index}}, {{option.divId}}, {{option.closeId}}</a>
</div>
</ng-template>
然后让选项匹配option:
, {option:{divId:'thumbnail-'+(this.divId++), closeId:'close-'+(this.closeId++)}}
是上下文对象,然后我可以使用option
在模板中为{{option.divId}}
。这里解释一下——Angular 2 中的 $implicit 是什么? https://stackoverflow.com/questions/45055384/what-is-implicit-in-angular-2
一旦我学会了如何通过模板传递数据,我就想到使用createEmbeddedView
并通过了index
到它,然后还用索引值更新视图的上下文对象。然后我可以稍后检索该值并将其用于remove
of ngContainerRef
删除该视图。这似乎最初有效,但在我存储视图 0,1,2,3 然后删除索引 1 后,容器将重新组织视图并为它们分配新索引。但是,上下文对象中的值没有更新。
因此,我不存储索引,而是存储ViewRef
在上下文对象中,当我想删除视图时,我调用indexOf
获取正确的索引值并将其用于remove
Code.
showTemplate(){
/*
You need to pass an object with the keys that match the let-keyname syntax:
The ng-template in html uses let-option and let-index so the object passed need to have index and option keys
*/
//create view and pass context data
let view:ViewRef = this.vc.createEmbeddedView(this.tmpl,
{option:{divId:'thumbnail-'+(this.divId++),
closeId:'close-'+(this.closeId++)
}} );
//after view is created, get its index and updat context. Note that ViewIndexRef was not in initial context object.
view.context.option.viewIndexRef = view;//store ref of this view
}
//pass the entier context object to the function
deleteIt(option){
//get viewRef from context and then get index of the viewref
let index = this.vc.indexOf(option.viewIndexRef)
//remove the view
this.vc.remove(index);
}
在html中,模板获取选项对象和click
的回调a
将其传递给deleteIt
功能
<ng-template #thumbnailTemplate let-option="option" let-index="index">
<div id="{{option.divId}}">
<img>
<a href="#" id="{{option.closeId}}" (click)="deleteIt(option)">template inserted at index {{option.index}}, {{option.divId}}, {{option.closeId}}</a>
</div>
</ng-template>