假如后台返回的字符串中有
html标签
时,我们希望可以直接将该标签渲染出来,而 Angular 中提供了[innerHTML]
内置指令来将字符串转为 HTML 代码
原因
但是基于 Angular官网 这里提到了:SecurityContext 标记了具有危险安全隐患的位置,比如,像 innerHTML 这样的 DOM 属性,如果处理不当,可能会导致跨站点脚本(XSS)安全错误。
因此如果在使用 [innerHTML]
指令时内部会自动将标签上的 style
属性去除掉,如下图:
检查元素也可以看到没有 style 属性
解决办法
stackoverflow 这里提到了可以通过管道来将不安全的字符串转为安全的 html 代码,具体如下:
新建一个 Safe.pipe.ts
文件:
import { Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({ name: 'safeHtml' })
export class Safe {
constructor(private sanitizer: DomSanitizer) { }
// 转为安全的html
public transform(html: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
在你需要使用该管道的组件 Module 中声明该管道:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { Safe } from '../common/function/safe.pipe';
/**
* 测试模块
*/
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
TranslateModule
],
declarations: [
Safe
],
providers: [],
exports: []
})
export class TestModule {
}
最后在组件中使用该管道即可:
<div [innerHTML]="sentence.content | safeHtml"></div>
这样就可以成功渲染样式了: