Skip to content

Aquent | DEV6

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Angular 2: HTML Binding

Written by: Alain Thibodeau

There will be a time when you need to render html that comes from somewhere outside of your template. Perhaps an html snippet sent from your server, or a snippet built at runtime. It may not be obvious at first how to achieve this but it is actually quite simple.

Given a property in your component of:

myHTML = ‘<b>This is my awesome bold text</b>’

First thing one would try is this:

<p> {{ myHTML }}</p>

Which would render this:

<b> This is my awesome bold text</b>

Not really what we wanted. This is because we are using interpolation when we should be using property binding.

Property Binding vs Interpolation

You can read more in the documentation, but the key difference that is applicable in our simple example is that interpolation evaluates the expression and will result in a string, whereas property binding does not convert the expression.

Therefore we should be binding to the ‘innerHTML’ property like this:

<p [innerHTML]="myHTML"> </p>

Which has better results:

This is my awesome bold text

It is also worth mentioning that Angular translates the interpolations to property bindings before rendering.

So this:

<div> Company: {{name}}</div>

Is “syntactic sugar” for this:

<div [textContent]="interpolate([‘Company’], [name])" > </div>

Syntactic sugar means that short form syntax is available to simplify more complex syntax. Either syntax can be used.

You can read more about template syntax in the Angular 2 documentation.

Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

view course details