Routing

https://angular.io/docs/ts/latest/guide/router.html

The Angular Router enables navigation from one view to the next as users perform application tasks.

It can interpret a browser URL as an instruction to navigate to a client-generated view and pass optional parameters along to the supporting view component to help it decide what specific content to present

Router Core Principle

Router Core Operations

https://vsavkin.com/angular-2-router

Simple Router Configuration Steps

  • ensure that base href is set in index.html
  • importing from the router library
  • configuring the router paths
  • inserting <router-outlet></router-outlet>
  • building simple navigation with routerLink directive
  • navigating from component's code

base href

The base tag tells the router how to compose navigation URLs.




<head>
  <base href="/">
				

Router imports

  • RouterModule - A separate Angular module that provides the necessary service providers and directives for navigating through application views.
  • Routes - Defines an array of Routes, each mapping a URL path to a component.
// AppModule.ts
import { RouterModule, Routes } from '@angular/router';
				

Paths configuration

 // AppModule.ts
const appRoutes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'heroes', component: HeroesComponent },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes)
  ],
  declarations: [ ... ],
  bootstrap: [ ... ]
})
				

Router Outlet


<router-outlet></router-outlet>

				

Router Link


<nav>
   <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
				

Navigating from component's code

 //*.component.ts
// import
import { Router } from '@angular/router';
...
// injection
constructor(private router: Router) {}
...
// navigation
this.router.navigate(['/dashboard']);
				

Main Navigation Example




				

Routing with path variables

  • configuring the router paths with variables
  • building navigation with routerLink directive
  • receiving params from a route

routes configuration


const appRoutes: Routes = [
  { path: 'hero/:id', component: HeroDetailComponent }
];
				

routerLink directive for paths with variables



<a *ngFor="let hero of heroes" [routerLink]="['/hero', hero.id]">
				

Receiving params from a path


import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';

export class HeroDetailsComponent implements OnInit {

  hero$: Observable<Hero>;

  constructor(
    private activatedRoute: ActivatedRoute,
    private heroService: HeroService
  ) { }

  ngOnInit() {
    this.hero$ = this.activatedRoute.params.pipe(
      switchMap(params => this.heroService.getHero(params.id))
    );
  }
}