To access route and query parameters in Angular, use the “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.
- Route params(Route parameters)
- Route queryParams(Route query parameters)
To pass values between views, you can use “route parameters.” For example, we can use route params if we pass an ID from one route to another and fetch the ID on a component onInit(). In real-world scenarios, based on the user ID, we can fetch the user profile details.
Angular Router provides an ActivatedRoute service that offers different observables through which we can access the URL parameters.
Accessing route parameters was never easy before, but now we have a robust Angular router API available to access the route params and even queryParams.
Passing Route params
Before defining new routes, let’s create two components.
- HomeComponent
- ProfileComponent
Type the following command to create Angular components.
ng g c home --standalone ng g c profile --standalone
We can define all the app-related routes inside the src/app/app.routes.ts file like this:
// app.routes.ts import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProfileComponent } from './profile/profile.component'; export const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'profile/:id', component: ProfileComponent }, ];
We have defined two routes. On the second route, we have passed a dynamic parameter ID.
Linking to Routes with Parameters
The routerLink directive passes an array that specifies the path and a route parameter.
Alternatively, we could navigate to the route programmatically. We will use the routerLink directive to navigate between different views.
Before going further, install the Angular material using the below command:
ng add @angular/material
Now, import the necessary material modules inside the src/app/app.component.ts file:
// app.component.ts import { Component } from '@angular/core'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { RouterModule, RouterLink, RouterLinkActive } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [ RouterModule, MatToolbarModule, MatButtonModule, RouterLink, RouterLinkActive, ], templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'Passing routing params'; }
Write the following code inside the app.component.html file.
<nav mat-toolbar color="primary"> <div class="navbar-content"> <a routerLink="/" class="navbar-brand" routerLinkActive="active"> AppDividend </a> <span class="spacer"></span> <div class="navbar-links"> <button mat-button [routerLink]="['/home']" routerLinkActive="active"> Home </button> <button mat-button [routerLink]="['/profile', 1]" routerLinkActive="active" > Profile </button> </div> </div> </nav> <div class="container"> <router-outlet></router-outlet> </div>
Also, add the CSS code inside the src/app/app.component.css file:
.navbar-content { display: flex; align-items: center; width: 100%; } .spacer { flex: 1; } .navbar-links { display: flex; } .navbar-brand { text-decoration: none; font-size: 24px; font-weight: bold; } .navbar-links button { margin-left: 10px; }
To navigate one route to another, we have used the routerLink directive.
In profile routerLink, you can see that we have passed two options.
- route pattern
- parameter: id
We can access the ID inside the src/app/profile/profile.component.ts file.
Accessing route params using ActivatedRoute
To access the route parameters of the current URL, use the “ActivatedRoute” service.
Write the following code inside the src/app/profile/profile.component.ts file.
import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-profile', standalone: true, imports: [], templateUrl: './profile.component.html', styleUrl: './profile.component.css', }) export class ProfileComponent { constructor(private route: ActivatedRoute) {} ngOnInit(): void { this.route.params.subscribe((params) => { console.log('The id of this route is: ', params['id']); }); } }
In this code, we have imported the ActivatedRoute module.
The profile.component.ts file must read the parameter and then load the profile based on the ID given in the parameter.
The ActivatedRoute service provides the params Observable, which we can subscribe to get the route parameters.
The params property on ActivatedRoute is Observable because the Router may not recreate a component when navigating to the same component.
Save the file, start the angular dev server, and go to this URL: http://localhost:4200/profile/1
Open the browser dev tools and go to the console part. You will see something like this.
The console shows that we got the value of id, which is 1. That is it. This is how you can access the current route parameter.
Passing Route queryParams
Query parameters mean whatever comes from after the question mark(?) in your URL.
We can pass the query parameters using the routerLink directive and programmatically.
Update the following code inside the src/app/app.component.html file.
<button mat-button [routerLink]="['/home']" [queryParams] = "{success: true}" routerLinkActive="active"> Home </button>
In the above code, you can see that we passed another option called queryParams in the home navigation. This option takes an object whose key is success and whose value is true.
Based on this parameter, we can display anything in the view. For example, we can display an alert message if the success condition is true.
Accessing query params
To access the queryParams inside the angular component, use the ActivatedRoute service that provides the queryParams Observable, which we can subscribe to get the query parameter values.
Write the following code inside the home.component.ts file.
// home.component.ts import { CommonModule } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; @Component({ selector: 'app-home', standalone: true, imports: [CommonModule, MatCardModule], templateUrl: './home.component.html', styleUrl: './home.component.css', }) export class HomeComponent implements OnInit { notify!: string; constructor(private route: ActivatedRoute) {} ngOnInit(): void { this.route.queryParams.subscribe((params) => { if (params['success'] === 'true') { this.notify = 'You have passed data'; } }); } }
You can see that inside the ngOnInit() method, we subscribe to the query params value and check for the condition.
We are setting a variable called notify.
If we get the success = true, we will set the component variable to notify and display the alert message in the view.
The last step is to display the alert message based on the notification message. So write the following code inside the home.component.html file.
<div *ngIf="notify" class="alert alert-success"> <mat-card class="mat-elevation-z4"> <mat-card-content> {{ notify }} </mat-card-content> </mat-card> </div> <p>home works!</p>
You can see that I have used the ngIf directive to display the conditional message based on the notify value.
And here is the src/app/home/home.component.css code:
.alert-success { background-color: #dff0d8; color: #3c763d; border-radius: 4px; padding: 15px; margin: 10px 0; } .mat-card { background-color: inherit; }
Save the file, go to http://localhost:4200/, and click on the home link; you will see something like this.
That is it. Remove the ?success=true from the URL, and you will see that the alert message is gone because our condition will be false and will no longer display.
This functionality is beneficial when you have to show a message indicating whether the user is logged in or logged out.
That’s it!