2016-09-16 46 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); 
}