Home » How to bind HTML inside the angular binding?

How to bind HTML inside the angular binding?

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

Leave a Comment

Your email address will not be published.

17 + 6 =