What is DomSanitizer in Angular?

Hamid Hassani
Mobiroller Tech
Published in
4 min readApr 25, 2023

Angular is a popular front-end framework for building dynamic web applications. One of the key features of Angular is its built-in support for security, which is essential for preventing cross-site scripting (XSS) attacks.

In Angular, the DomSanitizer service is used to sanitize and transform values, such as URLs and HTML fragments, to prevent XSS attacks. By using DomSanitizer, you can ensure that your Angular application is secure and protected from malicious code injections.

How does DomSanitizer work?

The DomSanitizer service provides a set of methods for sanitizing and transforming values in different ways. Here are some of the most commonly used methods:

  • bypassSecurityTrustHtml(): Sanitizes an HTML string and marks it as trusted, so that it can be rendered safely in the template.
  • bypassSecurityTrustStyle(): Sanitizes a CSS style string and marks it as trusted, so that it can be used safely in a style attribute.
  • bypassSecurityTrustScript(): Sanitizes a script string and marks it as trusted, so that it can be executed safely.
  • bypassSecurityTrustUrl(): Sanitizes a URL string and marks it as trusted, so that it can be used safely in a link or iframe.
  • sanitize(): Sanitizes an HTML, attribute, or style value, according to a specific security context.

Each of these methods takes a string value as input and returns a SafeHtml, SafeStyle, SafeScript, SafeUrl, or SafeValue object, respectively. These objects tell Angular that the value has been sanitized and is safe to use.

As an example, suppose you have an Angular component that displays the user’s profile picture, which is stored in a URL. To prevent XSS attacks, you can use DomSanitizer to sanitize the URL before rendering it in the template:

typescript
import { Component } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Component({
selector: 'app-profile',
template: `<img [src]="sanitizedUrl" alt="Profile picture">`
})
export class ProfileComponent {
public unsafeUrl: string = 'https://mobiroller.com/profile-picture.jpg';

constructor(private sanitizer: DomSanitizer) {}

public get sanitizedUrl(): SafeUrl {
return this.sanitizer.bypassSecurityTrustUrl(this.unsafeUrl);
}
}

Let me demonstrate another example that is related to urls:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { ApiService } from './api.service';

@Component({
selector: 'app-links',
template: `<h2>Links</h2>
<ul>
<li *ngFor="let link of links">
<a [href]="sanitizedUrl(link.url)" target="_blank">{{ link.title }}</a>
</li>
</ul>`
})
export class LinksComponent implements OnInit {

public links: any[];

constructor(
private apiService: ApiService,
private sanitizer: DomSanitizer) {}

ngOnInit(): void {
this.apiService.getLinks().subscribe((data: any[]) => this.links = data);
}

public sanitizedUrl(url: string): SafeUrl {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
}

So far so good, up to now we learned what is domSanatizer in Angular and how it basically works, it’s time to dive into more details, thereby let’s continue with describing sanitizer methods.

bypassSecurityTrustHtml()

As I said before the bypassSecurityTrustHtml() method is used to sanitize an HTML string and mark it as trusted so that it can be rendered safely in the template.

Here’s an example of how to use bypassSecurityTrustHtml() to render HTML in Angular:

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
selector: 'app-html-example',
template: `<div [innerHTML]="sanitizedHtml"></div>`
})
export class HtmlExampleComponent {

public unsafeHtml: string = '<p>Hello, <strong>world!</strong></p>';

constructor(private sanitizer: DomSanitizer) {}

public get sanitizedHtml(): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(this.unsafeHtml);
}
}

In this example, we’re using bypassSecurityTrustHtml() to sanitize the unsafeHtml string before rendering it in the template.

bypassSecurityTrustStyle()

I described before that The bypassSecurityTrustStyle() method is used to sanitize a CSS style string and mark it as trusted so that it can be used safely in a style attribute.

Here’s an example of how to use bypassSecurityTrustStyle() to apply CSS styles in Angular:

import { Component } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

@Component({
selector: 'app-style-example',
template: `<div [style]="sanitizedStyle">Hello, world!</div>`
})
export class StyleExampleComponent {

public unsafeStyle: string = 'color: red; font-size: 20px;';

constructor(private sanitizer: DomSanitizer) {}

public get sanitizedStyle(): SafeStyle {
return this.sanitizer.bypassSecurityTrustStyle(this.unsafeStyle);
}
}

In this example, we’re using bypassSecurityTrustStyle() to sanitize the unsafeStyle string before applying it to the style attribute in the template. The SafeStyle object returned by bypassSecurityTrustStyle() tells Angular that the CSS styles are safe to use.

bypassSecurityTrustScript()

The bypassSecurityTrustScript method is a part of Angular’s DomSanitizer service that allows developers to safely embed script elements in their templates. This method can be used to bypass the default security settings and trust a given script string, which can then be used in the HTML document.

Here’s an example of how to use the bypassSecurityTrustScript method in an Angular component:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
selector: 'app-script-example',
template: `<script [src]="trustedScript"></script>`,
})
export class ScriptExampleComponent {
public scriptString: string = 'console.log("Hello world!");';
publictrustedScript: any;

constructor(private sanitizer: DomSanitizer) {
this.trustedScript = this.sanitizer.bypassSecurityTrustScript(this.scriptString);
}
}

In this example, we have a component that contains a script element with a src attribute that is bound to a variable named trustedScript. This variable is initialized in the constructor using the bypassSecurityTrustScript method to trust a given script string.

The scriptString variable contains a simple script that logs “Hello world!” to the console. Normally, adding a script element to the HTML document in this way would be blocked by the browser’s security settings. However, by using the bypassSecurityTrustScript method, we are telling Angular to trust the script and allow it to be executed.

Note that the bypassSecurityTrustScript method should only be used when it is absolutely necessary to include script elements in your templates. Care should be taken to ensure that any script strings that are trusted using this method come from a trusted source, as they can potentially introduce security vulnerabilities in your application.

Conclusion

DomSanitizer is an important service in Angular that helps prevent XSS attacks by sanitizing and transforming values. By using DomSanitizer in your Angular applications, you can ensure that your application is secure and protected from malicious code injections.

--

--