How to Get All Route Params/Data in Angular?
Last Updated :
04 Jul, 2024
In Angular, managing route parameters and extracting data from routes is important for creating dynamic and responsive web applications. Route parameters allow you to pass information in URLs, and accessing this data enables your application to make decisions and render content dynamically. This article will guide you on how to get all route params/data in Angular
Prerequisites
Approach
- To access route parameters and data, we need to use Angular's 'ActivatedRoute' service. This service provides different observables. We can subscribe to required observables to get real-time updates of route parameters and data.
- We have created one Angular route file that contains the constant array of routing components along with path, component name and data. We have imported and registered it in the app module file. We will see the router path in the code later.
- We will create an app component and add navigation along with the routerLink in the component.
- We will create another component (product) on which we need to perform routing and get routing parameters and data using 'ActivatedRoute'.
- We will import the 'ActivatedRoute' and register it into the constructor. After registering, we will subscribe required observables which are 'paramMap' and 'data' to get information about the routing parameters and data. By subscribing to it we will get the information about the routing parameters and data.
We will see all the mentioned steps in the code base.
Steps to get Parameters and Data
Step 1: Install Angular CLI
- First you need to install Node.js on your system.
- Second, open your terminal or CMD(Command prompt) and run the below command
npm install -g @angular/cli
Step 2: Create a new Angular application
Run the below command to create a new Angular application
ng new angular-param-data --no-standalone
Step 3: Redirect to project directory
Change you working directory by entering project name in the below command
cd angular-param-data
Step 4: Execute an application
ng serve --open
The --open flag open an application directly in a browser. The application default run on http://localhost:4200.
The above mentioned steps create project with basic components and routes. It will generate app component along with the app routes. Now, we need create required Components and Module.
Step 5: Create product component
ng generate component product
The above command will create a component in the app directory. You can shorthand the command by writing ng g c.
The project directory structure will be display like the below image
Folder Structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^17.0.0",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/forms": "^17.0.0",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"@angular/router": "^17.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.2"
}
Example
JavaScript
//app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<header>
<nav>
<ul>
<li>
<a [routerLink]="['/']" routerLinkActive="active">Home</a>
</li>
<li>
<a [routerLink]="['/product', 4]" routerLinkActive="active">Product</a>
</li>
</ul>
</nav>
</header>
<router-outlet></router-outlet>`,
styleUrl: './app.component.css',
})
export class AppComponent {
title = 'angular-param-data';
}
JavaScript
//app.routes.ts
import { Routes } from '@angular/router';
import { ProductComponent } from './product/product.component';
export const routes: Routes = [
{
path: 'product/:id',
component: ProductComponent,
data: { info: 'Sample product page' },
},
];
JavaScript
//app.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';
import { routes } from './app.routes';
import { ProductComponent } from './product/product.component';
@NgModule({
declarations: [AppComponent, ProductComponent],
imports: [CommonModule, RouterModule.forRoot(routes), BrowserModule],
bootstrap: [AppComponent],
})
export class AppModule { }
JavaScript
//product.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product',
template: ` <h1>Example Component</h1>
<p>Current ID: {{ id }}</p>
<p>Route Data: {{ data }}</p>`,
})
export class ProductComponent implements OnInit {
id!: string | null;
data!: string;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
// For getting route parameter 'id'
this.activatedRoute.paramMap.subscribe((params) => {
this.id = params.get('id');
});
// For getting route data
this.activatedRoute.data.subscribe((data) => {
this.data = data['info'];
});
}
}
Output
How to get route params/data in Angular?The above example shows how to get route parameters and data in Angular.
Similar Reads
How to Handle Route Parameters in Angular?
In Angular, routing plays an important role in building single-page applications (SPAs). Often, you need to pass data between components through the URL using route parameters. Route parameters allow you to define dynamic segments in your routes, which can be extracted and used in your components. T
3 min read
How to detect a route change in AngularJS ?
In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/vi
2 min read
How to Create a new module in Angular ?
Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read
How to determine active route in AngularJS ?
In this article, we will see how to determine the active route in AngularJS, along with understanding the basic implementation through the example. Approach: To determine which is the active route at any moment in AngularJS this can be achieved by using $on() & $location.path() method. An event
2 min read
How to Get Page Load Time in Angular?
In web development, performance is the most important thing. Users expect fast and responsive web applications and even minor delays can impact user experience and satisfaction. Monitoring page load time is important for identifying performance bottlenecks and optimizing the user experience. In this
5 min read
How to handle Route Parameters in Express ?
Route parameters in ExpressJS capture dynamic values from URLs, like /users/:userId. These values are accessible in your route handler via req.params, enabling dynamic content generation. This allows for creating reusable routes that handle various inputs with a single pattern. [GFGTABS] JavaScript
4 min read
How to force redirect to a particular route in angular?
Introduction: We can use the property binding concept and we can pass query parameters to routerLink. Using Property binding we can bind queryParams property and can provide the required details in object. Property Binding: It is a concept where we use square bracket notation to bind data to Documen
3 min read
How to Navigate Fragment URL in Angular 15?
Fragment navigation is important in Angular applications for creating deep linking and bookmarking functionality within a single-page application (SPA). It allows users to navigate directly to specific sections or components within a page without reloading the entire page, enhancing user experience
3 min read
How to create module with Routing in Angular 9 ?
Angular applications are modular, and NgModules is Angular's own modular architecture. NgModules are containers for closely integrated application domains, workflows, or feature sets that comprise cohesive code blocks. Their scope is governed by the NgModule they include, and they can contain compon
4 min read
How to setup 404 page in angular routing ?
To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. Creating Component: Run the below command to create pagenotfound component. ng
2 min read