Route Parameter

Passing route parameter

const APP_ROUTES: Routes = [
  { path: 'user/:id', component: UserComponent }
];

In html

<a [routerLink]="['user', 10]">User</a>

Receiving route parameter

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

@Component({
  template: `
      User Id is {{ userId }}
    `
})
export class UserComponent{
  userId: string;

  constructor(private activatedRoute: ActivatedRoute) {
    this.userId = activatedRoute.snapshot.params['id']; 
  }
}

Note:

When you are on same route /user/10 and change route parameter from 10 to 12 ( anything else ) value won't update in html as constructure called only once when you navigated to this route

Fix for above problem

import { Component, OnDestroy } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import {Subscription} from 'rxjs/Rx';

export class UserComponent implements OnDestroy{
  userId: string;
  subscription: Subscription;

  constructor(private activatedRoute: ActivatedRoute) {
    this.subscription = activatedRoute.params.susscribe((param: any) => {
        this.userId = param.id;
    }); 
  }

  ngOnDestroy(){
      this.subscription.unsubscribe();
  }
}

Last updated

Was this helpful?