How to bind raw html in Angular2

Angular

Angular Problem Overview


I use Angular 2.0.0-beta.0 and I want to create and bind some simple HTML directly. Is is possible and how?

I tried to use

{{myField}}

but the text in myField will get escaped.

For Angular 1.x i found hits for ng-bind-html, but this seems not be supported in 2.x

thx Frank

Angular Solutions


Solution 1 - Angular

Bind to the innerHTML attribute

There is 2 way to achieve:

<div [innerHTML]="myField"></div>
<div innerHTML="{{myField}}"></div>

To mark the passed HTML as trusted so that Angulars DOM sanitizer doesn't strip parts of

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

with a pipe like

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

  transform(value: any, args?: any): any {
    return this.sanitizer.bypassSecurityTrustHtml(value);
    // return this.sanitizer.bypassSecurityTrustStyle(style);
    // return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
  }
}

See also https://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax/37076868#37076868

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfbenoitView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow