Multiple instances of the same root application in Angular 2

后端 未结 2 865
栀梦
栀梦 2021-01-03 03:45

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

相关标签:
2条回答
  • 2021-01-03 04:06

    That's currently not supported. There is an open issue to allow to override the selector when bootstrap() is called.

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

    0 讨论(0)
  • 2021-01-03 04:08

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题