Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Angular HTML binding

I'm composing an Angular application and I have an HTML reaction I need to show.

How do I do that? If I simply use the binding syntax {{myVal}} it encodes all HTML characters (of course).

I need in one way or another to bind the innerHTML of a div to the variable value.
by

2 Answers

kshitijrana14
The correct syntax is the following:
<div [innerHTML]="theHtmlString"></div>
sandhya6gczb
For safe content just

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

DOMSanitizer

Potential unsafe HTML needs to be explicitly marked as trusted using Angulars DOM sanitizer so doesn't strip potentially unsafe parts of the content

<div [innerHTML]="myVal | safeHtml"></div>

with a pipe like

@Pipe({name: 'safeHtml'})
export class Safe {
constructor(private sanitizer:DomSanitizer){}

transform(style) {
return this.sanitizer.bypassSecurityTrustHtml(style);
//return this.sanitizer.bypassSecurityTrustStyle(style);
// return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
}
}

Login / Signup to Answer the Question.