Angular 7 LazyLoading with children of children

Viewed 352

I may struggle to articulate the problem, but I do have a StackBlitz to help.

https://stackblitz.com/edit/angular-brhyir

Notice the Lazyloading 'users'...

app.routes.ts

//import { NgModule } from '@angular/core';
import { Routes } from '@angular/router';
import { SecureComponent } from './layouts/secure.component';
import { HelloComponent } from './hello.component';

//SECURE
export const SECURE_ROUTES: Routes = [
{ path: '',
  component: HelloComponent,
  data: {
  }
},

//Lazyloading
{ path: 'users',
  data: {
  breadcrumb: 'Users',
},
loadChildren: './users/user.module#UserModule' }
];

export const routes: Routes = [
 { path: '', component: SecureComponent, data: { title: 'Secure Views' }, 
 children: SECURE_ROUTES },

];

this works, but...

user.routes. ts

import { Routes } from '@angular/router';
import { UsersComponent } from './users.component';
import { UserComponent } from './user/user.component';
import { UserTwoComponent } from './user/user-two.component';

export const UserRoutes: Routes = [

  { path: '',
  component: UsersComponent,
  children: [
    {
      path: 'user',
      component: UserComponent,
      data: {
        breadcrumb: 'New'
      },
      children: [
        {
          path: 'user2',
          component: UserTwoComponent,
          data: {
            breadcrumb: 'New2'
          }
        }
      ]
    }
   ]
  }
];

So if you click the buttons you will witness the problem. Which is, the route is correct (users/user) BUT it does NOT load the 'UserComponent', instead it still shows the 'UsersComponent'. Why I do not know?

2 Answers

You have to have a <router-outlet></router-outlet> in the template of any target components that will render child routes.

Both UsersComponent and UserComponent have no <router-outlet> to render other routes.

There are three issues:

  1. In the users.component.ts, you need to make a small modification

    toUser() {
       this.router.navigate(['user'], {relativeTo: this.route});
    }
    

    This is needed to tell angular to route you to a certain path that is relative to the current path you are on.

  2. Same thing in the user.component.ts,

    toUserTwo() {
       this.router.navigate(['user2'], {relativeTo: this.route});   
    }
    

    For both these points to work you need to inject the ActivatedRoute in the respective constructors. You need to import it from @angular/router

  3. Next, you need to add the following in the user.component.html as well as the users.component.html

    <router-outlet></router-outlet>
    

    This is needed to render child routes in the parent template.

Here's the stackblitz if you need to see a working example of it.

Related