How to translate HTML string to real HTML element by ng-for in Angular 2?

Simplest solution:

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

Where some_string can be html code, e.g: some_string = "<b>test</b>".

No pipes or anything needed. Supported by Angular 2.0


In angular2 there's no ng-include, trustAsHtml, ng-bind-html nor similar, so your best option is to bind to innerHtml. Obviously this let you open to all kind of attacks, so it's up to you to parse/escape the content and for that you can use pipes.

@Pipe({name: 'escapeHtml', pure: false})
class EscapeHtmlPipe implements PipeTransform {
   transform(value: any, args: any[] = []) {
       // Escape 'value' and return it
   }
}

@Component({
    selector: 'hello',
    template: `<div [innerHTML]="myHtmlString | escapeHtml"></div>`,
    pipes : [EscapeHtmlPipe]
})
export class Hello {
  constructor() {
    this.myHtmlString = "<b>This is some bold text</b>";
  }
}

Here's a plnkr with a naive html escaping/parsing.

I hope it helps :)

Tags:

Html

Angular