Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass and get parameter with routerLink in Angular 2?

I want to pass a value with url using routerLink. And read that value on another page. Like I have product list. On select of first record the id of that record pass to product detail page. After read that productId I want to show detail of that product.

So How can I pass and get the parameter?

like image 831
MohammedAshrafali Avatar asked Feb 13 '17 10:02

MohammedAshrafali


3 Answers

you can use this in .html

[routerLink]="['/trips/display/' + item.trip, {'paramKey': 'application'}]"

and in .ts you can use this to recover the params

this.id = this.route.snapshot.params['id'];
const param = this.route.snapshot.params['paramKey'];
like image 118
user2652810 Avatar answered Oct 11 '22 02:10

user2652810


I'm assuming you have some code like this:

{ path: 'product/:id', component: ProductDetailComponent }

in ProductList template

<a [routerLink]="['/product', id]">Home</a>

or

<a [routerLink]="['/product', 5]">Home</a>

where id is a variable, maybe you got it in a loop.

in ProductDetailComponent:

constructor(
  private route: ActivatedRoute,
  private router: Router
) {}
ngOnInit() {

  this.route.params
    // (+) converts string 'id' to a number
    .switchMap((params: Params) => this.yourProductService.getProductById(+params['id']))
    .subscribe((product) => this.product = product);
}

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

like image 20
Tiep Phan Avatar answered Oct 16 '22 09:10

Tiep Phan


Use routerLink on your a tag for passing it by url.

[routerLink]="['yourRouteHere', {'paramKey': paramValue}]

To get it you need to use ActivatedRoute service. Inject it into your component and use it's subscribe method. Here my route is the injected service

this.route.params.subscribe(params => {
   const id = Number.parseInt(params['paramKey']);
}

If you want to get parameters from the route segment use .params, else if you want from query string, use .queryParams

like image 11
Suren Srapyan Avatar answered Oct 16 '22 10:10

Suren Srapyan