22

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?

Garry
  • 1,159
  • 3
  • 13
  • 22

5 Answers5

35

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

Vingtoft
  • 11,443
  • 17
  • 68
  • 114
30

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 :)

Community
  • 1
  • 1
Eric Martinez
  • 30,323
  • 8
  • 89
  • 90
  • 10
    Looks like the syntax is now `[innerHTML]`: http://stackoverflow.com/a/34424375/86937 – Josh Leitzel Feb 09 '16 at 18:52
  • 4
    This isn't sufficient for cases where your innerHTML actually contains angular-usable code. In my case, I want to be able to use [routerLink], but I can't. – thouliha Apr 29 '16 at 23:15
  • @thouliha did you ever figure out a solution to that? – Tucker Oct 23 '16 at 15:20
  • @Tucker nope. Once you use [innerHTML], you lose all templating abilities. Angular seems to really want you to do all your templating directly in static html. – thouliha Oct 24 '16 at 16:29
  • the solution in the plnkr is only for tag, how to handle for any(all) html tag? – Shaik Habeeb Apr 29 '21 at 07:26
4

I got Same Problem buy I Request the decode HTML from Backend and them you can inject html to 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>
Javier Perez
  • 158
  • 1
  • 8
0

The best solution which can be of your help is as below:

<p [innerHTML]=your_response_which_is_string></p>

Hope it helps!!!

sid7747
  • 453
  • 4
  • 11
-1

For property binding use below : <div innerHtml="{{ property }}"></div>

For just a string : <div [innerHtml]="<p>property</p>"></div>

him
  • 2,925
  • 3
  • 12
  • 17