Skip to content

Instantly share code, notes, and snippets.

@killerchip
Last active May 1, 2022 14:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killerchip/768fb34575003c430268db4bb64ee9ac to your computer and use it in GitHub Desktop.
Save killerchip/768fb34575003c430268db4bb64ee9ac to your computer and use it in GitHub Desktop.
Angular cheatsheet - How to create Angular nested routes

Nested Routes

The following describes how to create and use nested routes in Angular.

Example:

We have an e-shop with two main areas, the Home area and the Special Offers area. In special offers page we have two sub-pages: Today's Offers and Last Pieces offers.

Define which root routes will have child routes

routes.ts:

export const routes : Routes = [
    
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomePageComponent },
    { path: 'specials', component: SpecialOffersPageComponent, children: specialRoutes }

];

Define the sub-routes

special-routes.ts:

export const specialRoutes : Routes = [
    { path: '', redirectTo: 'today', pathMatch: 'full'},  //full path will be: '/specials'
    { path: 'today', component: TodayOffersComponent},    //full path will be: '/specials/today'
    { path: 'last', component: LastPiecesOffersComponent} //full path will be: will match '/specials/last'
];

Note: sub-paths consider that their root path is the parent route.

Use the router-outlet to render resutls

special-offers-page.component.html:

<h1>Special Offers !!!</h1>
<p>In this section you see our special offers...</p>

<!-- Here will be rendered the content of nested routes based on the '/specials' subpaths -->
<router-outlet></router-outlet>

Nav from parent to child

As "best practice" do not route to child subpath, but to child 'home' route and let the child route decide it's default. Remember that we defined a { path: ''... route in child routes.

app.component.html:

<!-- Navbar -->
<a [routerLink]="['home']">[HOME]</a>
<a [routerLink]="['specials']">[SPECIAL OFFERS]</a>

<!-- root content -->
<router-outlet></router-outlet>

Nav within the child routes area

Use paths as normal. The router will consider as start path the current path. In our example /specials/.

special-offers-page.component.html

<h1>Special Offers !!!</h1>

<a [routerLink]="['today']">[Today's Offers]</a>
<a [routerLink]="['last']">[Last Piecies]</a>

<hr>

<router-outlet></router-outlet>

Nav programmatically

import { ActivatedRoute, Router } from '@angular/router';

...

constructor(
  private router: Router,
  private activatedRoute: ActivatedRoute
){}

public navToOffer(id: number) {
  this.router.navigate(['./path', param], {relativeTo: this.activatedRoute} )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment