Angular16 min read

Angular Security Basics: XSS and Safe Rendering

Learn how Angular protects against XSS, when you must sanitize HTML, and common security mistakes.

Samantha Reed
August 26, 2025
7.0k304

XSS (Cross-Site Scripting) happens when attackers inject malicious scripts into your page, often through user-generated content.

Angular protects you by default in many cases, but you still need to understand safe patterns.

## Example: dangerous HTML rendering

If you do this:

```html
<div [innerHTML]="htmlFromApi"></div>
```

Angular will sanitize a lot of it, but you still should treat it carefully.

## Best practice

- Avoid rendering raw HTML unless you truly need it.
- Prefer structured content and templates.

## If you must render HTML

Use Angular’s sanitization tools, and only bypass security if you completely trust the source.

```ts
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

export class ArticleComponent {
  safeHtml: SafeHtml;

  constructor(sanitizer: DomSanitizer) {
    const htmlFromApi = '<p>Hello</p>';
    this.safeHtml = sanitizer.bypassSecurityTrustHtml(htmlFromApi);
  }
}
```

### Warning
`bypassSecurityTrustHtml` means “I trust this input.” Use it only when content is from a trusted pipeline.

> Next: Authentication patterns, JWT, interceptors, and route guards together.
#Angular#Security#Advanced