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.
- Author: Ahmed Bouchefra Follow @ahmedbouchefra
-
Date:
Related posts
How to send authorization header in Angular 14 Angular 14 Tutorial By Example: REST API & HttpClient GET Angular 14 route title and custom strategy Angular 14 inject example: reactive decorator Angular 14 inject How to enable CORS in Angular 14 Add Tailwind CSS to Angular 14 apps Import standalone components in Angular 14 Generate standalone components in Angular 14 Add Bootstrap to Angular 14 example Angular CLI 14 Render HTML with Angular and innerHtmlHands-on Angular eBook
Subscribe to our Angular newsletter and get our hands-on Angular book for free!
