Angular 2 Router Wildcard handling with child-routes

You can easily have a centralized wildcard route, i.e. for a site-wide 'Page not found' component. It simply has to be extracted into a separate routing module, which gets included after all the other modules containing child routes.

Therefore, the wildcard route is truly in last position and doesn't hide the routes from any following module.

The wildcard routing module or 'page not found' routing module:

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: '**',
                component: NotFoundComponent
            }
        ])
    ],
    declarations: [
        NotFoundComponent
    ],
    exports: [
        RouterModule
    ]
})
export class WildcardRoutingModule { }

The application module :

@NgModule({
    imports: [
        BrowserModule,

        AppRoutingModule, // Has forRoot routes 

        HomeModule, // Has forChild routes 
        LoginModule, // Has forChild routes
        ProductModule, // Has forChild routes
        DiagnosticsModule, // Has forChild routes

        WildcardRoutingModule // Last position
    ],
    declarations: [
        AppComponent  
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Simple solution is to reorder modules in the 'imports' array in app module file - ensure app/root router is the last item in the array; for example

@NgModule({
  imports: [FeatureModule1, FeatureModule2, FeatureModule3, AppRouterModule]
  ...
  ...
})

Tags:

Angular