How to translate HTML string into real HTML element using ng-for in Angular 2

As I know, in angular 1.x I can use the $ sce service to satisfy my requirement like this

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

and in the html file use this

 {{ htmlString || trustAsHTML }} 

Is there a service like $ sce or some channel or some method can be competent to do this in angularjs 2 version?

+19
html angular
Nov 02 '15 at 7:04
source share
4 answers

Angular2 doesn't have ng-include , trustAsHtml , ng-bind-html and nothing like that, so binding to innerHtml is the best option. Obviously, this allows you to open all types of attacks, so you decide to parse / avoid the content, and you can use channels for this.

 @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 plnkr with naive html escaping / parsing.

Hope this helps :)

+22
Nov 02 '15 at 11:07
source share

The simplest solution:

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

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

No pipes or anything else. Supported by Angular 2.0

+25
Sep 23 '16 at 9:06
source share

I got the same problem buy I request HTML decoding from Backend and you can enter them html on your page

 // YOUR TS @Component({ selector: 'page', templateUrl: 'page.html' }) export class Page { inject:any; constructor( ) { } ionViewDidLoad() { this.inject='your HTML code' } } 
 // YOU HTML PAGE <div [innerHTML]="inject"></div> 
+3
Nov 29 '16 at 21:05
source share

To bind the properties below: <div innerHtml="{{ property }}"></div>

For row only: <div [innerHtml]="<p>property</p>"></div>

-one
Jun 14 '17 at 6:38
source share



All Articles