Angular 2中相同根应用程序的多个实例

时间:2016-08-30 15:45:05

标签: angular

我们将Angular 2集成到遗留页面中,使功能逐个用户友好。到目前为止,为角度模块交换预渲染的后端小部件效果很好。

但是我遇到了一个我不知道要解决的问题:我编写了一个模块/组件,可以在页面上的不同位置和不同的配置上多次出现。

  <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>
案件的{p> Here is a Plunker。您只能看到初始化的第一个匹配项。有没有关于如何解决这个问题的概念?我想我不能使用包装器组件,因为我无法在其中移动整个模板(页面在后端呈现,而角度指令放在那里)。

干杯

2 个答案:

答案 0 :(得分:2)

感谢Tobias Bosch对github提供的一些指示,这是他提出的一个变通方法的调整版本:

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_。您需要直接导入它,因为默认情况下它不会在角度类型中导出。

或者您可以使用$('my-widget')(或您喜欢的任何其他选择器)来获取DOM引用,但我认为在组件上使用预定义选择器会更清晰。

答案 1 :(得分:1)

目前尚不支持。有一个未解决的问题,允许在调用bootstrap()时覆盖选择器。

https://github.com/angular/angular/issues/7136

相关问题