Intro

Prerequisites

  • Install Node.js.
  • Install angular-cli: npm i -g @angular/cli
  • Generate project: ng new angular-routing

Routing components in Angular

  • Routes defines the routes for application
  • RouterOutlet used in template and shows where to put the content of each route
  • RouterLink directive is used to link to routes

Import Modules

import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

Define routes

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'contactus', redirectTo: 'contact' }
];

Declare imports for Component

  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(routes),

    ProductsModule
  ],

Define template and add RouterOutlet

app.component.html:

<div class="page-header">
  <div class="container">
    <h1>Router Sample</h1>
    <div class="navLinks">
      <a [routerLink]="['/home']">Home</a>
      <a [routerLink]="['/about']">About Us</a>
      <a [routerLink]="['/contact']">Contact Us</a> |
      <a [routerLink]="['/products']">Products</a>
      <a [routerLink]="['/login']">Login</a>
      <a [routerLink]="['/protected']">Protected</a>
    </div>
  </div>
</div>

<div id="content">
  <div class="container">
    <router-outlet></router-outlet>
  </div>
</div>

Generate sample components

ng g c home ng g c about ng g c contact

Run app and see how it works

npm run start

Switching between location strategies

There are two main location strategies in Angular: * PathLocationStrategy (default HTML5 routing) - regular links: http://example.com/home * HashLocationStrategy - links include # sign: http://example.com/#/home

The main difference is when we refresh page in browser with HTML5-style routing, it will send ‘GET’ request with full URL to server (http://example.com/home) and server should properly handle the request redirecting to index page. But refreshing page with HashLocationStrategy won’t send full URL to server, only part before hash sign (http://example.com/#/home)

To switch to HashLocationStrategy, use this code:

  imports: [
  ...
    RouterModule.forRoot(routes, { useHash: true }),
  ...
  ]

Using Route parameters with Products Component

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

app.module.ts:

  { path: 'products', component: ProductsComponent },
  { path: 'products/:id', component: ProductsComponent }

Create Products component:

ng g c Products

Source code:

import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';

interface Product {
  title: string;
  price: number;
}

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {

  id: string;
  products: Product[] = [
    {
      title: 'Book',
      price: 10
    },
    {
      title: 'Pen',
      price: 2
    },
    {
      title: 'Pencil',
      price: 11
    }
  ];
  currProduct: Product;

  constructor(private route: ActivatedRoute) {
    route.params.subscribe(params => {
      this.id = params['id'];
      this.currProduct = this.getProductById(this.id);
    });
  }

  ngOnInit() {
  }

  getProductById(id: string): Product {
    if (id) {
      id = id.toLocaleLowerCase();
      return this.products.find( el => el.title.toLowerCase() === id );
    } else {
      return null;
    }
  }
}

HTML Markup:

<div *ngIf="!id">
  <h2>Product List</h2>
  <ul>
      <li *ngFor="let product of products"> <a routerLink="{{product.title}}"> {{ product.title }} </a> </li>
  </ul>
</div>

<div *ngIf="id">
  <h2>Product Info</h2>
  <p>Title: {{ currProduct.title }}</p>
  <p>Price: {{ currProduct.price }}</p>
</div>