How To Get The URL Parameters Using AngularJS?
Last Updated :
04 Jul, 2024
In AngularJS, retrieving URL parameters is essential for managing dynamic content and user interactions based on the URL state. In this article, we'll learn various approaches to achieve this.
Steps To Get URL Parameters
Step 1: Create a new Angular project
ng new my-angular-app
Step 2: Navigate to the project directory
cd my-angular-app
Step 3: Serve the application
ng serve
Project 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.13.0"
},
Approach 1: Using ActivatedRoute Service
Using Angular's ActivatedRoute service is a common and efficient way to access URL parameters in a component. This service provides access to the route's information, including query parameters, fragment, and data. By subscribing to the queryParams observable of ActivatedRoute, developers can reactively extract and utilize parameters from the URL.
This method ensures that any changes in the URL parameters are automatically reflected in the component, providing dynamic updates and enabling the component to respond to user actions or route changes without requiring manual URL parsing.
Example: In this example the parameter value is retrieved from the URL using ActivatedRoute and displayed.
HTML
<!-- app.component.html -->
<div>
<p>Parameter value: {{ paramValue }}</p>
</div>
JavaScript
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
paramValue: string | null = '';
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.paramValue = params['yourParam'];
});
}
}
Output
Approach 2: Using Router Service
Using the Router service in Angular to access URL parameters is another effective approach that provides direct access to the router's state. This method involves using the Router service to access the root state of the router and subscribing to the queryParams observable.
By doing this, developers can retrieve URL parameters and handle changes reactively, similar to the ActivatedRoute service. This method is particularly useful when you need to access or manipulate the router state more globally within the application, providing a centralized way to manage routing and navigation.
Example: In this example the parameter value is retrieved from the URL using Router Service and displayed.
HTML
<!-- app.component.html -->
<div>
<p>Your Name: {{ name }}</p>
</div>
JavaScript
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
name: string | null = '';
constructor(private router: Router) { }
ngOnInit(): void {
this.router.routerState.root.queryParams.subscribe(params => {
this.name = params['name'];
});
}
}
Output
Approach 3: Using URLSearchParams
Using the URLSearchParams method to retrieve URL parameters in an Angular application is a simple approach that uses the native JavaScript URLSearchParams object. This method allows you to parse the query string of the current URL directly without relying on Angular-specific services.
By accessing window.location.search, you can create a new URLSearchParams instance, which provides methods to conveniently extract query parameter values. This technique is simple and effective for scenarios where reactive updates to the URL parameters are not required.
Example: In this example the parameter value is retrieved from the URL using URLSearchParams and displayed.
HTML
<!-- app.component.html -->
<div>
<p>Your City: {{ city }}</p>
</div>
JavaScript
// app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
city: string | null = '';
ngOnInit(): void {
const queryParams = new URLSearchParams(window.location.search);
this.city = queryParams.get('city');
}
}
Output
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read