innerHTML Property Binding in Angular 2

Ever had properties in your component that contain some html markup or entities that you need to display in your template? The traditional interpolation won't work, but the innerHTML property binding comes to the rescue:

Given a property in our component like this:

export class SomeComponent {
  htmlStr: string = '<strong>The Tortoise</strong> &amp; the Hare';
}

We can bind to it and apply the markup with something like this in our template:

<div [innerHTML]="htmlStr"></div>

The Tortoise & the Hare

With interpolation instead of the property binding, {{ htmlStr }}, inside the div, we would have gotten this instead in the rendered view:

<strong>The Tortoise</strong> &amp; the Hare

👉 With both interpolation and property binding, Angular sanitizes the markup and prevents any script tags from being inserted.

Search

🔎 Searching...