如何在Angular 2中通过ng-for将HTML字符串转换为真实的HTML元素? [英] How to translate HTML string to real HTML element by ng-for in Angular 2?
问题描述
据我所知,在angular 1.x中,我可以使用$ sce服务来满足这样的要求
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);
};
}]);
并在html文件中使用这样的
and in html file use like this
{{ htmlString || trustAsHTML }}
在angularjs 2版本中,是否有诸如$ sce或某些管道之类的服务或任何方法都可以胜任?
Does there has a service like $sce or some pipe or any method can be competent to do that in angularjs 2 version?
推荐答案
在angular2中,没有 trustAsHtml
,ng-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.
我希望它可以帮助:)
这篇关于如何在Angular 2中通过ng-for将HTML字符串转换为真实的HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!