I’m building a simple Angular application where I’m experimenting with different ways of binding potentially unsafe content. Here’s the component code I’m using:
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1>Hello from {{ name }}!</h1>
href1: <a [href]="script1">Hello Script 1</a><br>
href2: <a [href]="script2">Hello Script 2</a><br><br>
template1: {{script1}}<br>
template2: {{script2}}<br><br>
innerHtml1: <span [innerHtml]="script1">Span 1</span><br>
innerHtml2: <span [innerHtml]="script2">Span 2</span><br>
`,
})
export class App {
name = 'Angular';
script1 = '<script>alert(1)</script>';
script2 = 'data:text/html,<script>alert(1)</script>';
}
bootstrapApplication(App);
I expected Angular to sanitize potentially dangerous values when binding them to elements, especially since Angular has built-in XSS protections. However, I noticed that the href attributes in my template are not sanitized. When I run this code, the href links with script1 and script2 are rendered directly into the HTML without any sanitization, potentially leading to security risks.
My Questions
- Why doesn’t Angular sanitize the href attribute by default when binding values?
- Is there a way to make Angular automatically sanitize href values, or do I need to manually sanitize them before binding?
- What is the best practice for handling dynamic href values in Angular to ensure security?
You can find a working example here: https://stackblitz.com/edit/stackblitz-starters-nklyjq?file=src%2Fmain.ts
1