如何在 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 服务来满足我这样的需求
myApp.filter('trustAsHTML', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
在html文件中这样使用
{{ htmlString || trustAsHTML }}
在 angularjs 2 版本中是否有类似 $sce 或某些管道的服务或任何方法可以胜任?
在 angular2 中没有 ng-include
、trustAsHtml
、ng-bind-html
也没有类似的,所以你最好的选择是绑定到 innerHtml
。显然,这会让您面临各种攻击,因此 parse/escape 内容取决于您,为此您可以使用管道。
@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 escaping/parsing.
希望对您有所帮助:)
最简单的解决方案:
<div [innerHTML]="some_string"></div>
其中some_string
可以是html代码,例如:some_string = "<b>test</b>"
.
不需要管道或任何东西。 Angular 2.0
支持
我在购买时遇到了同样的问题,我从后端请求解码 HTML,他们可以将 html 注入到您的页面
// 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>
对于 属性 绑定使用如下:
<div innerHtml="{{ property }}"></div>
对于一个字符串:
<div [innerHtml]="<p>property</p>"></div>
对您有帮助的最佳解决方案如下:
<p [innerHTML]=your_response_which_is_string></p>
希望对您有所帮助!!!
据我所知,在 angular 1.x 我可以使用 $sce 服务来满足我这样的需求
myApp.filter('trustAsHTML', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
在html文件中这样使用
{{ htmlString || trustAsHTML }}
在 angularjs 2 版本中是否有类似 $sce 或某些管道的服务或任何方法可以胜任?
在 angular2 中没有 ng-include
、trustAsHtml
、ng-bind-html
也没有类似的,所以你最好的选择是绑定到 innerHtml
。显然,这会让您面临各种攻击,因此 parse/escape 内容取决于您,为此您可以使用管道。
@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 escaping/parsing.
希望对您有所帮助:)
最简单的解决方案:
<div [innerHTML]="some_string"></div>
其中some_string
可以是html代码,例如:some_string = "<b>test</b>"
.
不需要管道或任何东西。 Angular 2.0
支持我在购买时遇到了同样的问题,我从后端请求解码 HTML,他们可以将 html 注入到您的页面
// 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>
对于 属性 绑定使用如下:
<div innerHtml="{{ property }}"></div>
对于一个字符串:
<div [innerHtml]="<p>property</p>"></div>
对您有帮助的最佳解决方案如下:
<p [innerHTML]=your_response_which_is_string></p>
希望对您有所帮助!!!