2016-09-16 70 views
0

我需要动态地将组件加载到可能位于我的app组件内部任何位置的HTML元素。Angular2从任何HTML元素获取模板参考

我打算使用TemplateRef作为ViewContainerRef.createEmbeddedView(templateRef)的参数来动态加载我所需的组件。

So I.E.我希望它可以看起来像这样

var myViewRef = this.viewContainer.createEmbeddedView(
    getTemplateRefFromNode(document.querySelector('.anySelector')) 
); 
this.resolver.resolveComponent(myComponent) 
    .then(factory => { 
    var newComponent = myViewRef.createComponent(factory, 0, myViewRef.injector); 
    }); 

回答

2

这不是它是如何工作的,根本不是。您没有TemplateRef关联的任何 DOM节点。 TemplateRef是由<template>元素创建的结构,仅有<template>元素。

很难提出替代建议,因为我不清楚你的意思是什么,“我需要动态地将组件加载到HTML元素中,这可能在我的应用程序组件中的任何地方。”

+0

第三方开发者正在开发插件,将其呈现在我们的网站之上。我希望允许这些开发人员为其组件的加载位置提供一个css选择器。你能想出一种方法来实现这一点吗?它是否能够在单独的视图中渲染组件,然后将节点移动到正确的位置? –

0

您是否试图将组件加载到组件内容的任意位置?

如果是这样,组件的内容中的某个位置会在元素上放置一个#loadLocation属性,那么组件中的此代码将会将您的自定义组件插入到该元素中。

@ContentChild('loadLocation',{read: ViewContainerRef}) loadLocation: ViewContainerRef; 

constructor(private componentFactoryResolver: ComponentFactoryResolver) {} 

ngAfterContentInit() { 
    if (!this.loadLocation) { 
    return; 
    } 
    let componentFactory = this.componentFactoryResolver.resolve(myComponent); 
    let newComponent = this.loadLocation.createComponent(componentFactory); 
}