Using innerHTML in angular 2+ project

Using innerHTML in angular 2+ project

Using innerHTML in angular 2+ project

innerHTML property is used to display the html content in your template.

You might be having some scenario where you’ll need to display the html template from string where the interpolation syntax won’t work because it will display html tag as plain text in the template. so in that case innerHTML will come into the place.

Now we’ll see how we can use innerHTML in angular(2+) project.

In component file, we’ve INNER HTML PROPERTY BINDING EXAMPLE text which is wrapped inside h1 tag and stored it in htmlCode variable. we want it to be displayed as html template inside the template.

<br />import { Component, OnInit } from '@angular/core';<br /><br />@Component({<br />  selector: 'app-root',<br />  templateUrl: './app.component.html',<br />  styleUrls: ['./app.component.css']<br />})<br />export class AppRootComponent implements OnInit {<br />    var htmlCode = "&lt;h1&gt;INNER HTML PROPERTY BINDING EXAMPLE&lt;/h1&gt;";<br />    <br />    constructor(){}<br /><br />    ngOnInit(){}<br />}<br />

To display htmlCode variable as html template, we’ll use innerHTML property as following.

<br />&lt;div [innerHtml]="htmlCode"&gt;&lt;/div&gt;<br />

This will return the output as follows:

Output:

INNER HTML PROPERTY BINDING EXAMPLE

Also Read:

Leave a Comment