Hello, here we are going to discuss how to prevent XSS attacks or Cross-Site Scripting in angular applications.
When we make any web application, then security is an important part of an application where we need to secure our web application from various attacks, one of which is an XSS attack or cross-site scripting attack.
What is XSS(Cross-Site Scripting)

XSS is a kind of injection attack. Let’s consider you have an application, and that application contains the contact form or registration form, where the user enters either their queries or their information in the input field or text Area field.
For example, what happens if a hacker gives a malicious script injected in the contact form text are Like the below script and clicks on submit
<script>alert(“XSS Attack");"</script>
Now, in this case, it will open a popup, and behind the screen, the website will send the request to the hacker’s computer with the current system cookies information or your crucial information will be in the attacker's system, even if you will not even realize it that XSS attack is happening.
Generally, an XSS attack happens on DOM elements (Object data model), like input, and text area Fields, so to prevent our website from an XSS attack we need to check whether the request contains the script or not, and if it contains then we need to handle such kind of condition.
How to prevent XSS attacks in Angular
When we create an angular application then there is also a chance to happen an XSS attack, so let’s understand it with an example.
XSS Escaping/bypass security in Angular
To prevent cross-site scripting (XSS) attacks in the angular application, we can use the built-in angular cross-site scripting (XSS) protection.
This is enabled automatically by the angular CLI.
Now let’s create an angular application and write the below code in app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Angular15Service } from './angular15.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular 15 App';
username = '';
constructor() {}
ngOnInit() {}
}
And write the below code in app.component.html
<p >{{title}}</p>
<label for="username">Name: </label>
<textarea id="username" [(ngModel)]="username" placeholder="Name"> </textarea>
<p>{{ username }}</p>
Here we can see, we are using Two-way data binding.
So when we give any value to the text area field, the same value we are printing in the paragraph using “interpolation”
When we are running the above code and give any value in TextArea then interpolation will not able to take input as HTML and display the full input as the plain text on your web application page, this mechanism is generally called “contextual escaping” like below




Join the conversation! Your thoughts help the community grow.