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

前端 未结 5 1670
走了就别回头了
走了就别回头了 2020-12-01 16:20

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(t         


        
相关标签:
5条回答
  • 2020-12-01 16:40

    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>

    0 讨论(0)
  • 2020-12-01 16:47

    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

    0 讨论(0)
  • 2020-12-01 16:48

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

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

    Hope it helps!!!

    0 讨论(0)
  • 2020-12-01 16:49

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

    0 讨论(0)
  • 2020-12-01 16:52

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

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

    0 讨论(0)
提交回复
热议问题