DEV Community

Red
Red

Posted on

How to add parameterized route in Angular

Suppose you have the requirement that you want to show list of users if the url is /user, and you want to show user detail of a particular user when the URL is /user/useId.

Soultion 1 - We could user querry params

To achieve this we can create a users component, then in its ngOnInit we could check if params are present.

/// Here route is ActivatedRoute

this.route.queryParams.subscribe(params => {

if(params.userId){
//// Do Something
console.log(params.userId);
}
});

Enter fullscreen mode Exit fullscreen mode

You can get the params like this and then write your logic accordindly. If params are present then show userDetails if not then list of users.

Solution 2 - Use parameterized route

Like So

const routes: Routes = [
  { path: '/user', component: UsersComponent },
  { path: '/user:userId', component : UserDetailsComponent}
];
Enter fullscreen mode Exit fullscreen mode

Here we are explicitly stating that if url is /user then show UsersComponent or if it is like /users/xxxid then show userDetials page.

This is more Systematic & preferred way of doing the task.

If you are using only one parameter then use parameterized route. But if you have many parameters then use querry Params as stated above in solution 1.

How to navigate to parameterized route from template

<a *ngFor="let user of users"
  routerLink="/user/{{user.id}}">
  {{user.name}}
</a>
Enter fullscreen mode Exit fullscreen mode

Assume we are having list users and clicking on a user name will open that particlular user details.

To get the value of ther parameter use ActivatedRoute

console.log(this.route.snapshot.paramMap.get('userId');
Enter fullscreen mode Exit fullscreen mode

Points To remember

If you are getting any error remember to recheck the route you had written. sometimes you append extra / like user/:userId/ or prepend extra slash (/) like /user/:userId.

Although you can use more then two parameters
like user/:userId/:id/:age
I would suggest to avoid it and if it cannot be avoided atleast limit it to two parameters.

Top comments (0)