Sub topic 14
Sanitization and Safe Binding Practices
Data binding moves values from your component into the DOM. When a value comes from a user, an API, or a URL parameter, it can contain markup or script that an attacker controls. Angular treats every bound value as untrusted by default and cleans it, or blocks it, before writing it to the page. This chapter explains how that protection works, where it stops, and which binding habits keep it in place.
This chapter assumes you know interpolation and property binding from earlier chapters, and that you understand what cross-site scripting (XSS) is: an attacker gets their script to run in another user's browser session.
Why Bindings Need Protection
Look at two bindings that seem to do the same thing:
import { Component } from '@angular/core';
@Component({
selector: 'app-comment',
template: `
<p>{{ comment }}</p>
<p [innerHTML]="comment"></p>
`,
})
export class CommentComponent {
comment = '<b>Nice post</b><img src="x" onerror="alert(document.cookie)">';
}The first paragraph shows the literal text, angle brackets included. Interpolation writes to the element's textContent, so the browser never parses the string as HTML. Text cannot run script, so no sanitization is needed.
The second paragraph binds to the innerHTML property, so the browser parses the value as markup. Angular sanitizes the value first. The <b> element survives, but the onerror attribute is removed. In development mode the console logs WARNING: sanitizing HTML stripped some content. The rendered output is a bold "Nice post" and an image with no event handler.
Security Contexts
Angular decides how to treat a value by looking at where it is bound. Each destination belongs to a security context. The compiler works out the context from the element and property names in the template.
| Context | Typical bindings | What Angular does with untrusted values |
|---|---|---|
| HTML | `[innerHTML]` | Parses and removes unsafe elements and attributes such as `<script>`, `on*` handlers and `javascript:` links |
| Style | `[style]`, `[style.prop]` | Writes the value as is. Modern browsers do not execute script from CSS, so Angular stopped altering styles in version 10 |
| URL | `<a [href]>`, `<img [src]>` | Allows normal schemes and prefixes unsafe ones, such as `javascript:`, with `unsafe:` so they do nothing |
| Resource URL | `<iframe [src]>`, `<script [src]>`, `<object [data]>` | Cannot be made safe by editing, so Angular throws an error unless the value is explicitly trusted |
| None | `[title]`, `[disabled]`, `[value]`, interpolation | No sanitization, because the browser treats these values as data |
The resource URL row catches people out most often. A resource URL loads and runs code from another origin. No amount of string cleaning makes an arbitrary URL safe to load as a script or frame, so Angular refuses it outright:
ERROR: NG0904: unsafe value used in a resource URL contextThis also applies to attribute bindings. [attr.href] on an anchor is sanitized as a URL, just as [href] is. The attr. prefix does not get around the security check.
Trusting Values Explicitly with DomSanitizer
Sometimes you need a value that Angular would block, such as an embedded video in an iframe. The DomSanitizer service from @angular/platform-browser provides methods that wrap a string in a marker object telling Angular to skip its checks:
bypassSecurityTrustHtmlbypassSecurityTrustStylebypassSecurityTrustUrlbypassSecurityTrustResourceUrlbypassSecurityTrustScript
Each method returns a typed wrapper, such as SafeResourceUrl. The wrapper only counts in its own context. A SafeHtml passed to an iframe src still fails, and dev mode reports the mismatch.
The names include "bypass" on purpose. Calling one of these methods means you have taken over the job of proving the value is safe. Never pass raw user input to them. Validate the value against a strict allowlist, then build the trusted string yourself.
The pipe below embeds a YouTube video. The user supplies only a video ID, never a URL. The pipe checks the ID's format and builds the full URL from a fixed origin.
import { Component, Pipe, PipeTransform, inject, signal } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;
@Pipe({ name: 'youtubeEmbed' })
export class YoutubeEmbedPipe implements PipeTransform {
private sanitizer = inject(DomSanitizer);
transform(videoId: string): SafeResourceUrl | null {
if (!VIDEO_ID.test(videoId)) {
return null;
}
const url = `https://www.youtube-nocookie.com/embed/${videoId}`;
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
@Component({
selector: 'app-video',
imports: [YoutubeEmbedPipe],
template: `
@if (videoId() | youtubeEmbed; as url) {
<iframe [src]="url" width="560" height="315" title="Video player"></iframe>
} @else {
<p>Invalid video ID.</p>
}
`,
})
export class VideoComponent {
videoId = signal('dQw4w9WgXcQ');
}The trust decision lives in one small, testable place. A pure pipe also returns the same wrapper object while the ID stays the same, so the iframe does not reload on every change detection pass. A method call that creates a new wrapper each time could make the iframe reload repeatedly.
Sanitizing on Demand
You can also call the sanitizer yourself, for example when you pass a value to a third-party library that writes to the DOM:
import { Component, SecurityContext, inject } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-preview',
template: `<p>Sanitized length: {{ clean.length }}</p>`,
})
export class PreviewComponent {
private sanitizer = inject(DomSanitizer);
clean = this.sanitizer.sanitize(
SecurityContext.HTML,
'<i>ok</i><script>alert(1)</script>'
) ?? '';
}sanitize returns the cleaned string. It returns null for a null input. If you give it a SafeValue wrapper of the matching type, it returns the value unchanged.
Where Angular's Protection Ends
Sanitization only covers values that go through template bindings. These patterns skip it:
| Pattern | Why it is unsafe | Safer alternative |
|---|---|---|
| `elementRef.nativeElement.innerHTML = value` | Direct DOM write, Angular never sees it | `[innerHTML]` binding |
| `renderer.setProperty(el, 'innerHTML', value)` | `Renderer2` does not sanitize | Sanitize first with `DomSanitizer.sanitize`, or use a binding |
| Building template strings from user input and compiling them at runtime | User input becomes template code and can run expressions | Keep templates static and pass user data in through bindings |
| Server-rendered HTML that mixes user input into Angular templates | The server creates template syntax such as `{{ }}` that Angular will evaluate | Escape output on the server and keep the Angular template static |
| `document.write`, `eval`, `new Function` | Run arbitrary code | Avoid them completely |
Template injection deserves extra attention. Angular templates are code. If an attacker can put {{ ... }} into a template before it is compiled, sanitization never applies, because the attacker's text is now part of the program. Ahead-of-time (AOT) compilation, the default in the Angular CLI, compiles templates at build time, so this only happens if you deliberately build templates at runtime or let a server insert raw input into them.
Defense in Depth with Trusted Types and CSP
Browsers that support Trusted Types can enforce at the platform level that only approved code writes to dangerous sinks such as innerHTML. Angular registers its own policies, so a Content Security Policy (CSP) header like this one works with an Angular app:
Content-Security-Policy: trusted-types angular angular#unsafe-bypass; require-trusted-types-for 'script';The angular policy covers values Angular has sanitized itself. The angular#unsafe-bypass policy covers values passed through the bypassSecurityTrust* methods. If you leave out angular#unsafe-bypass, any bypass call fails at runtime, which is a useful way to confirm your app never uses one. Any third-party code that writes to innerHTML directly then fails loudly instead of quietly opening a hole.
A Safe Binding Checklist
- Show user text with interpolation, not
[innerHTML]. - Let Angular sanitize HTML and URLs. Treat the dev-mode "stripped some content" warning as a bug report and look into it.
- Call
bypassSecurityTrust*only on values you built from validated, allowlisted parts, and keep that code in one pipe or service. - Write to the DOM through bindings, not through
nativeElementorRenderer2with raw strings. - Keep templates static and compile them ahead of time.
- Add a CSP with Trusted Types for browser-level enforcement.
Exercise
A component binds <a [href]="profile.website">Website</a>, and a user sets their website to javascript:alert(1). What does Angular render, and what changes if the binding is [attr.href] instead?
Show answer
Angular sanitizes the value in the URL context and renders href="unsafe:javascript:alert(1)", so clicking the link does not run script, and dev mode logs a sanitization warning. Using [attr.href] changes nothing, because attribute bindings on href are sanitized in the same URL context.
Exercise
A developer writes <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl(userUrl)"> to fix an NG0904 error. Name two problems with this code and describe a better design.
Show answer
First, it trusts an arbitrary user-supplied URL, so an attacker can frame any page or load a malicious origin, which defeats the resource URL check. Second, calling the method in the template creates a new SafeResourceUrl on every change detection pass, which can make the iframe reload. A better design takes only a validated identifier, checks it against a strict pattern or allowlist, builds the URL from a fixed trusted origin, and wraps it once in a pure pipe or a computed value.
Exercise
Your app sets the CSP trusted-types angular; require-trusted-types-for 'script'. A component uses [innerHTML]="html" with a plain string, and another uses bypassSecurityTrustHtml. Which one breaks, and why?
Show answer
The bypass one breaks. Plain [innerHTML] values are sanitized by Angular and pass through the allowed angular policy. Bypassed values go through the angular#unsafe-bypass policy, which this CSP does not list, so the browser blocks the assignment.