Angular 2+ supports an [innerHTML] property for render a html content in HTML, if you are using interpolation than it will treat as a string
in this article, I will explain you how to use [innerHTML] to render a HTML string in Angular
Binding using innerHTML
For example if you have any that contains a HTML elements and string data like below
export class AppComponent {
htmlString: string = 'This is simple string <b>Bold string</b>';
}
if you are print this variable with interpolation:
<div>{{ htmlString}}</div>
The above code will produce the result like this
This is simple string <b> Bold string </b>
See above, HTML tag h1 is not rendered in DOM
Now we are using [innerHTML] property to render a string like below
<div [innerHTML]="htmlString"></div>
After compiling, this code will produce the result:
This is simple string Bold string
innerHTML with DOMSanitizer
[innerHTML]
uses Angular’s DomSanitizer
which uses a list of approved HTML elements and attributes. sometimes string contain some special tags than it will not work so for bypass this process we can use below code, Lets do with pipe like this
@Pipe({name: 'safeHtml'})
export class Safe {
constructor(private sanitizer:DomSanitizer){}
transform(mixString) {
return this.sanitizer.bypassSecurityTrustHtml(mixString);
}
}
Use the above in angular template like this
<div [innerHTML]="myVal | safeHtml"></div>
Related Post
- How to use material chips(tags) in Angular?
- How to implement material spinner in Angular?
- Angular 12 autocomplete with API Data
- Angular 12 TinyMCE integration with an example
- Angular 12 Material Tabs Tutorial with Example
- Angular 12 Material Autocomplete Example
- Angular 12 Material Dialog Example
- How to bind HTML inside the angular binding?
- Angular 12 Bootstrap Responsive Carousel slider
- Angular 12 modal popup example with Bootstrap 4