Angular 2中同一根应用程序的多个实例 [英] Multiple instances of the same root application in Angular 2
问题描述
我们将Angular 2集成到旧版页面中,以使该功能逐步变得更加用户友好.到目前为止,将预渲染的后端小部件交换为angular模块效果很好.
we integrate Angular 2 into a legacy page to make the functionality piece by piece more user friendly. So far exchanging prerendered backend widgets for angular modules has worked great.
但是我遇到了一个我不知道要解决的问题:我编写了一个模块/组件,该模块/组件可以在页面上的不同位置和使用不同的配置多次出现.
However I ran into a problem that I don't know to solve: I have written a module/component that can occur multiple times on the page at different locations and with a different configuration.
<body>
<div class='somewhere-on-the-page'>
<my-widget config='A'></my-widget>
</div>
<div class='somewhere-else-on-the-page'>
<my-widget config='B'></my-widget>
</div>
</body>
这里是案件的老头子.您可以看到只有第一次出现被初始化.关于如何解决这个问题有什么概念吗?我想我不能使用包装器组件,因为我无法在其中移动整个模板(页面在后端呈现,而角度指令放置在其中).
Here is a Plunker of the case. You can see only the first occurrence is initialised. Is there any concept on how to tackle this? I think I cannot use a wrapper component since I cannot move the whole templating inside it (pages are rendered in the backend and angular directives are put in there).
欢呼
推荐答案
感谢Tobias Bosch在github上给出的一些建议,这是他提出的解决方法的调整版本:
Thanks to Tobias Bosch for some pointers he gave on github, this is a adjusted version of a workaround he proposed:
import {ApplicationRef_} from '<project-root>/node_modules/@angular/core/src/application_ref'
@NgModule({
imports: [BrowserModule],
declarations: [MyWidgetComponent],
entryComponents: [MyWidgetComponent]
})
class MyWidgetModule {
constructor(injector: Injector, cfr: ComponentFactoryResolver, appRef: ApplicationRef) {
const widgetCompFactory = cfr.resolveComponentFactory(MyWidgetComponent);
$(widgetCompFactory.selector).each((_, el) => {
var compRef = widgetCompFactory.create(injector, [], el);
var upcasted = <ApplicationRef_> appRef;
upcasted.registerChangeDetector(compRef.changeDetectorRef);
});
}
}
请注意从角度文件中导入ApplicationRef_
.您需要直接将其导入,因为默认情况下在角度输入中未将其导出.
Take care to import ApplicationRef_
from the angular file. You need to import it directly since it's not exported by default in the angular typings.
或者,您可以使用$('my-widget')
(或其他任何选择器)来获取DOM引用,但是我认为在组件上使用预定义的选择器会更干净.
Alternatively you can use $('my-widget')
(or any other selector you please) to get your DOM references, but I think it's cleaner to use the predefined selector on the component.
这篇关于Angular 2中同一根应用程序的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!