Having paramterised routes work

Last Updated on

1>> In the app-routing.module.ts file add a paramter to a route using colon and paramter, in the example below, the id:

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

2>> In the component where this id is to be utilized, impoty ActivatedRoute from @angular/router:

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

3>> In the constructor of this same class, subscribe to the route.params and start working with the parameter, in this case the id:

 constructor(private route: ActivatedRoute) { 
                this.route.params.subscribe( params => {
                          console.log("- got params.id: " + params.id);
                           this.itemId = params.id 
                });
              }

  itemId: number;
  

* * *

A good example can be found at:

https://codecraft.tv/courses/angular/routing/parameterised-routes/

Lämna ett svar