Back to results for “Security”
Angular › Angular Security (XSS, Sanitization & CSP)

What is cross site scripting, often called XSS, and how does Angular protect against it by default?

Beginner

Answer

Cross site scripting happens when an attacker manages to inject malicious code into a page, which then runs in another user's browser, often stealing information or performing unwanted actions. Angular protects against this automatically by treating any value you bind through normal template interpolation as plain text, safely escaping special characters instead of running them as code.
@Component({
  selector: 'app-comment',
  template: `<p>{{ comment }}</p>` // Angular automatically escapes this safely
})
export class CommentComponent {
  comment = 'Hello there'; // even suspicious looking input is displayed as safe plain text
}
Real-world example A blog's comment section safely displays user submitted comments containing suspicious looking text, because Angular automatically escapes it as plain text instead of accidentally running it as real code in another visitor's browser.

Common follow-ups: What specifically does Angular do differently from directly inserting text into the DOM using plain JavaScript?;Are there any situations where Angular's automatic protection does not apply?