Menu Search Me

Angular Routing

Defining a basic routing module

src/app/app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { CrisisListComponent } from './crisis-list/crisis-list.component';
import { HeroListComponent } from './hero-list/hero-list.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'heroes', component: HeroListComponent },
  //empty path route: if there is no path, redirect to path '/heroes'
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  //wildcard route: if the path is not any of above, route to PageNotFoundComponent
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
    appRoutes,
    { enableTracing: true } // <-- debugging purposes only
    )
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

NOTE:

The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.

If you need to see what events are happening during the navigation lifecycle, there is the enableTracing option as part of the router's default configuration. This outputs each router event that took place during each navigation lifecycle to the browser console. This should only be used for debugging purposes. You set the enableTracing: true option in the object passed as the second argument to the RouterModule.forRoot() method.

Using routes in component templates

app.component.html

<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>

NOTE:

  • The router-outlet tag serves as a placeholder where the routed components will be rendered in it.
  • routerLinkActive is a directive that lets you add a CSS class to an element when the link's route becomes active.

Route parameters with matrix URL

If you want to use route parameters in matrix URL, your route definition does not have to change:
{ path: 'hero', component: HeroDetailComponent }

And you can access this route with URL like below, where id and foo are the 2 parameters:
http://localhost:4200/hero;id=19;foo=foo

And you can navigate to the route with the 2 parameters by creating a link in the component template like below:

<a [routerLink]="['/hero', { id: hero.id, foo: 'foo' }]">
  <span class="badge">{{ hero.id }}</span>{{ hero.name }}
</a>

Navigating routes and using route parameters (matrix url) in component

import { Router, ActivatedRoute, ParamMap } from '@angular/router';
......
constructor(
  private route: ActivatedRoute,
  private router: Router,
  private service: HeroService
) {}
......
ngOnInit() {

  let id = this.route.snapshot.paramMap.get('id');
  let foo = this.route.snapshot.paramMap.get('foo');

  this.hero$ = this.service.getHero(id);
}
......
//navigating routes with no parameter
gotoHeroes() {
  this.router.navigate(['/heroes']);
}
......
//navigating routes with 2 parameters
//Browser address bar should look something like this, depending on where you run it:
//localhost:4200/heroes;id=15;foo=foo
//This is matrix URL notation
gotoHeroesWithParameter(hero: Hero) {
  let heroId = hero ? hero.id : null;
  this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}

Route parameters with query parameters

If you want to use route parameters with query parameters, your route definition does not have to change:
{ path: 'hero', component: HeroDetailComponent }

And you can access this route with URL like below, where id and foo are the 2 parameters:
http://localhost:4200/hero?id=19&foo=foo

And you can navigate to the route with the 2 parameters by creating a link in the component template like below:

<a [routerLink]="['/hero']" [queryParams]="{id: hero.id, foo: 'foo'}" queryParamsHandling="merge">
  <span class="badge">{{ hero.id }}</span>{{ hero.name }}
</a>

NOTE:

  • queryParamsHandling="merge" means the query parameters you specifies in the routerLink will be added to current parameters (in your browser address bar)
  • queryParamsHandling="preserve" means the query parameters you specifies in the routerLink will be ignored and current parameters (in your browser address bar) will be passed
  • If you do not specify queryParamsHandling, it means only the query parameters you specifies in the routerLink will be passed.

Navigating routes and using route parameters (query parameters) in component

import { Router, ActivatedRoute, ParamMap } from '@angular/router';
......
constructor(
  private route: ActivatedRoute,
  private router: Router,
  private service: HeroService
) {}
......
ngOnInit() {

  let hid = ""
  let fool = ""
  this.route.queryParams.subscribe(params => {
    hid = params['hid'] || 'not found';
    fool = params['fool'] || 'not found';
  });
  console.log(hid)
  console.log (fool)
  this.hero$ = this.service.getHero(hid)

}
......
//navigating routes with no parameter
gotoHeroes() {
  this.router.navigate(['/heroes']);
}
......

gotoHeroesWithParameter(hero: Hero) {
let heroId = hero ? hero.id : null;
this.router.navigate(['/superheroes'], {queryParams: {debug: true, id: hero.id, fools: 'fool'}, queryParamsHandling: "merge"});
}

NOTE:

  • queryParamsHandling="merge" means the query parameters you specifies in the router.navigate function will be added to current parameters (in your browser address bar)
  • queryParamsHandling="preserve" means the query parameters you specifies in the router.navigate function will be ignored and current parameters (in your browser address bar) will be passed
  • If you do not specify queryParamsHandling, it means only the query parameters you specifies in the router.navigate function will be passed.