What is the difference between interpolated content and innerHTML?

In Angular, interpolation is a technique used to evaluate an expression and insert its resulting value into the text in a view. It allows you to display a component property in the corresponding view template with double curly braces, like this: {{ myProperty }}.

The innerHTML is a property of an HTML element that sets or returns the HTML content of an element. In Angular, the innerHTML property can be used to set the HTML content of an element to the specified HTML string.

The main difference between interpolated and innerHTML code is the behavior of code interpreted. Interpolated content is always escaped i.e, HTML isn't interpreted and the browser displays angle brackets in the element's text content. Where as in innerHTML binding, the content is interpreted i.e, the browser will convert < and > characters as HTMLEntities. For example, the usage in template would be as below,

<p>Interpolated value:</p>
<div>{{htmlSnippet}}</div>
<p>Binding of innerHTML:</p>
<div [innerHTML]="htmlSnippet"></div>

and the property defined in a component.

export class InnerHtmlBindingComponent {
htmlSnippet = 'Template <script>alert("XSS Attack")</script> <b>Code attached</b>';
}

Even though innerHTML binding create a chance of XSS attack, Angular recognizes the value as unsafe and automatically sanitizes it.


August 21, 2022
2240