且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Angular 2中通过ng-for将HTML字符串转换为真实的HTML元素?

更新时间:2023-10-10 18:12:58

在angular2中,没有 trustAsHtmlng-bind-html或类似名称,因此***的选择是绑定到innerHtml.显然,这使您可以接受所有类型的攻击,因此您可以解析/转义内容,并可以使用管道.

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>";
  }
}

这是一个 plnkr ,其中包含未使用过的html转义/解析功能.

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

我希望它可以帮助:)