Search code examples
angularangular-routingangular-router

Nested routing: how to route inside a route?


I'm trying to create a nested route (I believe this is the term for it).

With one main route which supplies four entirely different pages (main-component.html is just the router outlet tags).

And inside the first route path, i want to have in one part of the page (center div) a second routing which will be navigated by arrow buttons (forward and backward). The content for this div is complex (including communication with a backend server) so a construction with *ngIf and different templates is not ideal).

Can this be done with two routes? And if so, how?


Solution

  • It can be done like this:

    import { Routes, RouterModule }   from '@angular/router';
    
    import { FirstComponent, 
             SecondComponent,
             ThirdComponent,
             FourthComponent
    } from './app.component';
    
    const appRoutes: Routes = [        
        {
            path: 'first',
            component: FirstComponent,
            children:[
            {
             path : 'second',
             component: SecondComponent,
             children:[
               {
                path : 'fourth',
                component: FourthComponent
               },
               {
                path : 'third',
                component: ThirdComponent
               }
             ]
            }
           ]
         },
         {
            path: '',
            redirectTo: '/first',
            pathMatch: 'full'
        },
    ];
    

    and components:

    import { Component }          from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
        <h3 class="title">Routing</h3>
        <hr />
        <router-outlet></router-outlet>
      `
    })
    export class AppComponent {
    }
    
    
    @Component({
      template: `
        <h3 class="title">FirstComponent</h3>
        <nav>
        </nav>
        <hr />
        <router-outlet></router-outlet>
      `
    })
    export class FirstComponent {
    }
    
    @Component({
      template: `
        <h3 class="title">SecondComponent</h3>
        <nav>
          <a routerLink="second" routerLinkActive="active" >Second</a>
          <a routerLink="third" routerLinkActive="active" >Third</a>
        </nav>
        <hr />
        <router-outlet></router-outlet>
      `
    })
    export class SecondComponent {
    }
    
    @Component({
      template: `
        <h3 class="title">ThirdComponent</h3>
      `
    })
    export class ThirdComponent {
    }
    
    @Component({
      template: `
        <h3 class="title">FourthComponent</h3>
        <hr />
      `
    })
    export class FourthComponent {
    }