【问题标题】:Multiple instances of the same root application in Angular 2Angular 2 中同一根应用程序的多个实例
【发布时间】:2016-08-30 15:45:05
【问题描述】:

我们将 Angular 2 集成到旧版页面中,以使功能更加用户友好。到目前为止,用 Angular 模块交换预渲染的后端小部件效果很好。

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

  <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 的案例。您可以看到只有第一次出现被初始化。有没有关于如何解决这个问题的概念?我认为我不能使用包装器组件,因为我无法在其中移动整个模板(页面在后端呈现,并且在其中放置了角度指令)。

干杯

【问题讨论】:

    标签: angular


    【解决方案1】:

    感谢 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);
        });
      }
    }
    

    注意从 Angular 文件中导入 ApplicationRef_。您需要直接导入它,因为默认情况下它不会在角度类型中导出。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-20
        • 1970-01-01
        • 1970-01-01
        • 2020-11-14
        相关资源
        最近更新 更多