Render HTML with Angular and innerHtml

Render HTML with Angular and innerHtml

Angular 14 provides a [innerHTML] property binding that you can use to render HTML instead of using interpolation, which will, as you might have noticed, render any HTML string as a plain text.

In this post, you will be taught how to utilize [innerHTML].

Let's begin by discussing why you would wish to bind HTML within an Angular 14 component. You might need to render some user-generated HTML within the DOM. You may even receive HTML as a response from an API. Or you might have HTML that must be displayed dynamically.

What's innerHTML

The innerHtml attribute is a standard HTML element attribute to which Angular 14 can bind with square brackets i.e [ & ].

How to use innerHtml with Angular 14

Suppose for the sake of this example that you are dealing with a component that has a string property containing some HTML content:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  htmlContent = '<h1>Hello Angular 14!</h1>';
  constructor() { }
}

If we use interpolation to display the htmlContent property in the associated template as follows:

<div></div>

We'll get something like the follows:

<h1>Hello Angular 14!</h1>

The HTML elements are not rendered but simply displayed as plain text.

Now, let's change that to use the following syntax in our template:

<div [innerHtml]="htmlContent"></div>

After saving the template, you'll see the following:

Hello Angular 14!

Conclusion

Due to the fact that Cross-Site Scripting can be introduced when HTML is rendered. HTML that has been rendered may include malicious scripts that pose a security risk.

Limiting HTML elements and attributes to a set of recognized safe elements and attributes is one way for tackling XSS.

Behind curtains, [innerHTML] utilizes Angular's DomSanitizer, which checks HTML elements and attributes against a list of permitted elements and attributes.


✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

✋ Want to master Angular 14? Read our angular tutorial and join our #DailyAngularChallenge where we learn to build components, directives, services, pipes and complete web, mobile, and desktop applications with latest Angular version.

✋ Make sure to join our Angular 14 Dev Community 👈 to discuss anything related to Angular development.

❤️ Like our page and subscribe to our feed for updates!