Garry Garry - 5 days ago 7
HTML Question

How to translate html string to real html element by ng-for in angular 2

As I know, in angular 1.x I can use $sce service to meet my requirment like this

myApp.filter('trustAsHTML', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);


and in html file use like this

{{ htmlString || trustAsHTML }}


Does there has a service like $sce or some pipe or any method can be competent to do that in angularjs 2 version?

Answer

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 [inner-html]="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 :)

Comments