SoFunction
Updated on 2025-04-10

Methods for binding using innerHTML attribute in Angular

Introduction

Angular 2+ supports use[innerHTML]Properties binding to render HTML. If you use interpolation, it will be treated as a string.

This article will introduce how to use it[innerHTML]And some precautions.

Prerequisites

If you want to learn from this article, you need:

  • It would be more helpful to have some understanding of Angular interpolation and property binding.

Step 1 — Using innerHTML

Suppose you are working on a component that contains a string that is mixed with plain text and HTML entities and elements:

export class ExampleComponent {
  htmlStr: string = 'Plain Text Example &amp; <strong>Bold Text Example</strong>';
}

Let's consider a template that uses interpolation on this string:

<div>{{ htmlStr }}</div>

After compilation, this code will produce the following results:

Plain Text Example & <strong>Bold Text Example</strong>

HTML entities and HTML elements are not rendered.

Now, let's consider a template that uses the [innerHTML] attribute binding on this string:

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

After recompiling, this code will produce the following results:

Plain Text Example & Bold Text Example

Notice that HTML entities and HTML elements are rendered.

Step 2 — Understanding the limitations

Rendering HTML often introduces the potential risks of cross-site scripting attacks (XSS). Rendered HTML may contain malicious scripts, posing a security issue.

One way to solve XSS is to limit the types of HTML elements and attributes, allowing only a set of known "safe" elements and attributes.

Behind the scenes, [innerHTML] uses Angular's DomSanitizer, which uses a set of approved HTML elements and attributes.

This will limit your [innerHTML] values ​​from using <script> and <style> tags and style attributes. Keep this restriction in mind when choosing to use [innerHTML].

in conclusion

In this article, you learned about Angular 2+[innerHTML]Usage of attribute binding. It will render the HTML tags contained in the string.

This is the article about using innerHTML attribute binding in Angular. For more related Angular innerHTML attribute binding content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!