I am writing an Angular application and I have an HTML response I want to display.
How do I do that? If I simply use the binding syntax {{myVal}}
it en
The correct syntax is the following:
<div [innerHTML]="theHtmlString"></div>
Documentation Reference
Just to post a little addition to all the great answers so far: If you are using [innerHTML]
to render Angular components and are bummed about it not working like me, have a look at the ngx-dynamic-hooks library that I wrote to address this very issue.
With it, you can load components from dynamic strings/html without compromising security. It actually uses Angular's DOMSanitizer
just like [innerHTML]
does as well, but retains the ability to load components (in a safe manner).
See it in action in this Stackblitz.
Please refer to other answers that are more up-to-date.
This works for me: <div innerHTML = "{{ myVal }}"></div>
(Angular2, Alpha 33)
According to another SO: Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2), "inner-html" is equivalent to "ng-bind-html" in Angular 1.X
We can always pass html content to innerHTML
property to render html dynamic content but that dynamic html content can be infected or malicious also. So before passing dynamic content to innerHTML
we should always make sure the content is sanitized (using DOMSanitizer
) so that we can escaped all malicious content.
Try below pipe:
import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";
@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value: string) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
Usage:
<div [innerHTML]="content | safeHtml"></div>
If you want that in Angular 2 or Angular 4 and also want to keep inline CSS then you can use
<div [innerHTML]="theHtmlString | keepHtml"></div>
Working in Angular v2.1.1
<div [innerHTML]="variable or htmlString">
</div>