Site Overlay

How to render and sanitize HTML inside div with innerHTML in Angular 9/8?

0

When building an Angular 9 application with an HTML markup that you need to render.
How do you do that?
If you simply use regular binding i.e {{var}} this will encode all HTML characters. Is there a simple solution to render an HTML string in your Angular template?

1
0

You can render and sanitize an HTML string in your Angular 9 template using property binding with the innerHTML property of a div element.  

Let’s consider the following htmlString variable in our Angular 9 component:

export class MyComponent {
  htmlString: string = '<b>Hello Angular 9</b>';
}

We can render the HTML markup in the string variable using the following code:

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

We’ll get the following output:

Hello Angular 9

We use property binding around the innerHTML property of the div element.

If you use interpolation i.s {{ htmlString }}, inside the div, we’ll get:

<b>Hello Angular 9</b> 

Please note that in both interpolation and property binding, Angular 9 will sanitize the markup to prevent any security issues.