Skip to content

Instantly share code, notes, and snippets.

@killerchip
Last active July 29, 2018 08:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killerchip/4d75c51eb3344f2bbc92ac744fd17891 to your computer and use it in GitHub Desktop.
Save killerchip/4d75c51eb3344f2bbc92ac744fd17891 to your computer and use it in GitHub Desktop.
Angular cheatsheet - Defining and reading route parameters

Route parameters

Defining and reading route parameters

Define the parameter in routes

app.component.ts:

const routes: Routes = [
  {path: 'products/:id', component: ProductsComponent }
];

Grab the parameter using ActivatedRoute

products.ts:

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

export class ProductComponent {

  public productId: number;

  constructor(
    private activatedRoute: ActivatedRoute
  ) {
      //parameter query is returned via Observable
      this.activatedRoute.params.subscribe(
        params => { this.productId = params['id']; }
      )

   }

Send params to router links

If you want to use [routerLink] to send parameters, here's how you do it:

an HTML template:

  <!-- 
    we assume a link for product with id = 123
    the 'id' typically will be built dynamically,
    inside a *ngFor statement
   -->
  
  <a [routerLink]="['/products', '123']">Product nr. 123</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment