To access route parameters and query parameters in Angular, use ActivatedRoute service. The ActivatedRoute service provides Observables through which we can subscribe to the values of route params and route query params.

In Angular, we can pass the data as route parameters in two ways.

  1. Route params(Route parameters)
  2. Route queryParams(Route query parameters)

If we want to pass values between views, then we can use route params. For example, if we’re going to pass an ID from one route to another and fetch the id on a component onInit(), then we can use route params. In real-world scenarios, based on the userID, we can fetch the user profile detail.

Angular Router provides an ActivatedRoute service that offers different observables through which we can access the URL parameters.

Accessing route params are never easy before, but now we have available robust Angular router API through which we can access the route params and even queryParams.

How to Pass Angular Route params

When we install a new angular project, we have to enable the routing. That will create a file called **app-routing.module.ts **file.

Before defining new routes, let’s create two components.

  1. HomeComponent
  2. ProfileComponent

Type the following command to create Angular 10 components.

ng g c home --skipTests=true
ng g c profile --skipTests=true

Now, we can define all the app related routes inside that file. So let’s define some routes there.

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'profile/:id', component: ProfileComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule { }

You can see that we have defined two routes, and on the second route, we have passed a dynamic parameter Id.

#angular #route params #queryparams #activatedroute

Angular Route Params: How to Pass Route Params in Angular
1.55 GEEK