Loading episodes…
0:00 0:00

Render HTML with Angular and innerHtml

00:00
BACK TO HOME

Render HTML with Angular and innerHtml

ahmed April 21, 2022 2 min read

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.


Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Audio Interrupted

We lost the audio stream. Retry with shorter sentences?