102

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

0

1 Answer 1

225

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 In RC.1 some styles can't be added using binding syntax

Sign up to request clarification or add additional context in comments.

19 Comments

i am using the same thing to prevent it from stripping the click event, but now the click event wont fire, i have seen other answers stating for a dynamic event click, but how do i make the click work in this simple situation mentioned above
You can't add anything Angular-specific using [innerHTML]="..." binding. The only way to make this work is to create and compile a component at runtime.
stackoverflow.com/questions/35080387/… angular way of event listen "NICE STUFF"
I'm not sure if this is an update to the spec, but in Angular 5+, it is now DomSanitizer from @angular/platform-browser and not Sanitizer, which is an @angular/core class.
@GünterZöchbauer Yes I agree, I just wanted to point this out so people think about it first and not just copy the pipe in all cases.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.