使用Angular 2.0(最终版),在应用程序引导和组件渲染发生后,如何在非Angular库中创建的DOM元素中加载Component
?
我之前使用
DynamicComponentLoader.loadNextToLocation()
在DOM元素中加载了组件,但从RC5开始就弃用了。
问题(TL; DR)
我尝试使用Angular 2.0在弹出窗口中插入一个动态创建的Component,该窗口由运行时由外部非Angular库生成(特别是,InfoWindow/Popup
用于ESRI ArcGIS JavaScript API 3.x
地图)。
由于弹出窗口完全由外部库在 app bootstrap
之后生成,并且父组件的ngAfterViewInit()/ngAfterContentInit()
事件发生,因此任何#ref
新添加的弹出窗口中存在的标记将被忽略。如果没有#ref
标记和派生的ViewContainerRef
,我无法弄清楚如何在弹出窗口中插入新的组件。
我使用this SO answer中显示的相同设置,即:
@ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef})
protected dynamicComponentTarget: ViewContainerRef;
// this will be reference to dynamic content - to be able to destroy it
protected componentRef: ComponentRef<IHaveDynamicData>;
this.compiler
.compileComponentAsync<IHaveDynamicData>(dynamicType, MyModule)
.then((factory: ng.ComponentFactory<IHaveDynamicData>) =>
{
// our component will be inserted after #dynamicContentPlaceHolder
this.componentRef = this.dynamicComponentTarget.createComponent(factory, 0);
// and here we have access to our dynamic component
let component: IHaveDynamicData = this.componentRef.instance;
component.entity = this.entity;
});
注意:基于@MarkRajcok的帖子here,我有理由尝试
ChangeDetectorRef.detectChanges()
触发重新渲染父组件,希望{{1}新创建的弹出窗口中的标签将被拾取和编译。但是,由于我对Angular 2.0缺乏经验,我到目前为止没有运气。也许这是一种误入歧途的方法?
答案 0 :(得分:1)
我做到了这一点,但感觉就像完全破解......它确实将组件渲染到dom元素位置,但
var me = this;
setTimeout(function(){
var simpleComponent = me.componentFactoryResolver.resolveComponentFactory(SimpleComponent);
me.componentRef = me.dynamicTarget.createComponent(simpleComponent);
var node = document.getElementById("theTest");
node.appendChild(me.componentRef['_hostElement'].nativeElement);
}, 10);