Sunday, April 26, 2020

Angular children route configuration

For angular project, route configuration is used to decide which component should be loaded for the current path.

For app-routing.module.ts, the logic is quite simple, if the current url matches an item in routes configuration, then that component will be loaded in the <router-outlet></router-outlet> element specified in app.component.html.

Component can be either lazy loaded or normal loaded. In the below sample, component Com1 is lazy loaded, so the app-routing configuration only indicates which module (Com1Module) should be loaded, once the module is loaded, the module's route configuration will decide which component defined in the module will be loaded. On other hand, if a component is normal loaded, like Comp2Component for path com2, then the route configuration directly indicate which component should be loaded.

app-routign.module.ts

const routes: Routes = [  {    path: 'com1',    loadChildren: () => import('./com1/com1.module').then( m => m.Com1Module)  },  {    path: 'com2', component: Com2Component,    children: [      {        path: 'sub1',        component: Com2sub1Component      },      {        path: 'sub2',        component: Com2sub2Component      }    ]  },
];

In case the matched component's html file contains another

If the loaded component's html file contains a <router-outlet></router-outlet> element, then the route item can use children property to specify which a sub component path to be loaded into this new <router-outlet> element, this works in the same way for both lazy load and normal load. The below shows the com1 components' html and route module file.

Com1.component.html

<p>com1 works!</p><div><a routerLink="sub1" routerLinkActive="active">com1 sub1</a><br><a routerLink="sub2" routerLinkActive="active">com1 sub2</a></div><router-outlet></router-outlet>


Com1-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: Com1Component,
    children: [
      {
        path: 'sub2',
        loadChildren: () => import('../com1sub2/com1sub2.module').then(m => m.Com1sub2Module)
      }
    ]
  },
  {
    path:'sub1',
    loadChildren: () => import('../com1sub1/com1sub1.module').then( m =>m.Com1sub1Module)
  }
];