3

I need to pass id as parameter to my angular component

In my html i have something like this

<a [routerLink]="['/viewjobdetail',  currentJob.id]">
    {{ currentJob.title }}
</a>

app.module.ts RouterModule.forRoot configured as

  { path: 'viewjobdetail/:id', component: JobDetailComponent }

in my calling component i have

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute){}

ngOnInit(): void {
this.route.queryParams.subscribe(params => {
  debugger;
  var a = params['id'];
  this.displayJobId = parseInt(params['id']);
});

But when i check it its always showing undefined for a, what i am doing wrong here? }

2 Answers 2

2

You should use params or paramMap instead of queryParams, query params can only recognise query params passed like viewjobdetail?id=23

queryParams is better since params may be deprecated in future releases

this.route.paramMap.subscribe(paramMap => {
  debugger;
  var a = paramMap.get('id');
  this.displayJobId = parseInt(a);
});
3
  • So if i am going with queryParams, how should i declare it in my html a tag? Jan 9, 2021 at 8:11
  • 1
    @NithinPaul If you want to use queryParams in your HTML, use it as explained in this post Jan 9, 2021 at 8:16
  • Just updated the code in my answer i mistakenly used the queryParams instead of paramMap, In additional to Ruben comment, if you used paramMap you don't need to change anything in the html
    – Nichola
    Jan 9, 2021 at 8:20
1

I got the solution. to achieve thiswe need to use query parameters with queryParams. I modified my html as below

<a [routerLink]="['/viewjobdetail']" [queryParams]="{id: currentJob.id}">
{{ currentJob.title }}
</a>

and in app.module.ts

{ path: 'viewjobdetail', component: JobDetailComponent }

and then in my calling component

  this.route.queryParams.subscribe(params => {
  
  var a = params.id;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.