Search code examples
angulartypescriptangular8angular-routercustom-element

Angular Router ignores URL, when using custom ngDoBootstrap and createCustomElement


WHEN I use custom ngDoBootstrap function instead of default bootstrap: [AppComponent] like this:

@NgModule({
  imports:      [ BrowserModule, FormsModule, AppRoutingModule ],
  declarations: [ AppComponent, HelloComponent ],
  exports: [ AppComponent ],
  entryComponents: [ AppComponent ],
  // bootstrap: [AppComponent],
})
export class AppModule {
  constructor(private injector: Injector) {
  }

  public ngDoBootstrap(): any {
    const appElement = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('my-app', appElement);
  }
}

THEN Application routing is broken.

It ignores any changes in the URL and only works when I click on <a [routerLink]='...'>. Also the initial route / is not loaded.

It must be caused by the custom bootstrap mechanizm, because when I uncomment the bootstrap: [AppComponent], everything works fine.

Full code is available here: stackblitz sample (needs to be downloaded and run locally because of typescript version used by stackblitz)

How to make the routing work with custom app module bootstrapping?


Solution

  • in case of custom element, router.initialNavigation had to be called manually:

    export class AppModule {
      constructor(private injector: Injector, private router: Router,
        private location: Location) {
        const appElement = createCustomElement(AppComponent, { injector: this.injector });
        customElements.define('my-app', appElement);
    
    
      public ngDoBootstrap(): void {
        // workaround for bug - initial route not loaded: https://github.com/angular/angular/issues/23740
        this.router.initialNavigation();
      }
    }