How to Add Special Characters in URL in Angular?
Last Updated :
09 Jul, 2024
When developing web applications with Angular, you might encounter situations where you need to include special characters in URLs. Special characters such as spaces, ampersands, question marks, and others often need to be encoded correctly to ensure the URL is valid and functions as expected. In this article, we'll explore how to add special characters in URLs in Angular, ensuring they are properly encoded.
Understanding URL Encoding
URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding involves replacing unsafe ASCII characters with a "%" followed by two hexadecimal digits.
For example:
- Space:
%20
- Ampersand:
%26
- Question mark:
%3F
Steps to Create an Angular Application
Step 1: Install Angular CLI
npm install -g @angular/cli
Step 2: Create a Angular application using the following command
ng new my-angular-app
cd my-angular-app
Step 3: Run the Application
ng serve
Project Structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Handling Special Characters in URLs
If we use special character in URLs directly, they can lead to unexpected behavior. Instead of using them directly we will use encodeURIComponent function which is used to encode special characters so that they can be used in URL's without any issues. Let's start with Angular's Router for Navigation.
Approach 1: Using Angular Router for Navigation
Create a new file named special-chars-navigation.component.ts and add the following code:
JavaScript
// special-chars-navigation.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-special-chars-navigation',
template: `<button (click)="navigateWithSpecialChars()">Navigate</button>`,
})
export class SpecialCharsNavigationComponent {
constructor(private router: Router) { }
navigateWithSpecialChars() {
const specialChars = 'hello@world';
this.router.navigate(['search'], {
queryParams: { search_query: encodeURIComponent(specialChars) },
});
}
}
Update the app-routing.module.ts as well. It should look like this:
JavaScript
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SpecialCharsNavigationComponent } from './special-chars-navigation.component.ts'
const routes: Routes = [
{
path: 'search', component: SpecialCharsNavigationComponent
}
]
Output: When you click on the navigate button, you can see the character encoded URL in the browser.
Using angular router's navigationApproach 2: Manual Encoding for External Links
Create a new file named manual-encoding.component.ts and add the following code:
JavaScript
// manual-encoding.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-manual-encoding',
template: `<a [href]="url" target="_blank">External Link</a>`
})
export class ManualEncodingComponent {
url: string;
constructor() {
const specialChars = 'manual@encoding';
const encodedSpecialChars = encodeURIComponent(specialChars);
this.url = `https://geekforgeek.com/search?q=${encodedSpecialChars}`;
}
}
Update the app-routing.module.ts as well. The routes should look like this:
JavaScript
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ManualEncodingComponent } from './manual-encoding.component.ts'
const routes: Routes = [
{
path: 'search', component: ManualEncodingComponent
}
];
Output: When you click on the External Link it will redirect you to the respective url with the special character encoded.
Manual Encoding for External LinksApproach 3: Using Angular's HttpClient for API Calls
Create a new file named http-client-example.component.ts and add the following code:
JavaScript
// http-client-example.component.ts
import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
@Component({
selector: 'app-http-client-example',
template: `<button (click)="makeRequest()">Make API Request</button>`
})
export class HttpClientExampleComponent {
constructor(private http: HttpClient) { }
makeRequest() {
const specialChars = 'hello@world';
const params = new HttpParams().set('query', encodeURIComponent(specialChars));
this.http.get('https://api.example.com/search', { params })
.subscribe(response => {
console.log(response);
});
}
}
Update the app-routing.module.ts as well. The routes should look like this:
JavaScript
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientExampleComponent } from './http-client-example.component.ts'
const routes: Routes = [
{
path: 'search', component: HttpClientExampleComponent
}
];
Make sure to import HttpClientModule in app.module.ts
Output: When you will click on the Make API Request button you can see the API call in the console. It will give error as expected, I don't have any API in the backend.
Using Angular's HttpClient for API CallsConclusion
- Angular Router: Automatically handles URL encoding when navigating within the app.
- External Links: Use encodeURIComponent to manually encode special characters.
- HttpClient: Automatically handles URL encoding when using HttpParams.
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. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
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
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
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
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 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
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it 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. In this article we will explore what
10 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read