angular中绑定的innerHtml内部样式不起作用的问题

问题:使用innerHtml绑定的内容在页面上不显示相应的样式

如:

listItem = "测试<span >红色</span>字体";

<div [innerHtml]="listItem"></div>

在浏览器中查看时,div中的内容是"测试<span>红色</span>字体",定义的样式没有了

解决:使用pipe

safe-html.pipe.ts

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({ name: 'safeHtml' })
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) { }
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}

safe-html.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SafeHtmlPipe } from "@shared/pipe/safe-html/safe-html.pipe";
@NgModule({
imports: [
CommonModule,
],
declarations: [SafeHtmlPipe],
exports: [SafeHtmlPipe]
})
export class SafeHtmlModule{ }
引入SafeHtmlModule,将<div [innerHtml]="listItem"></div>改为<div [innerHtml]="listItem | safeHtml"></div>即可。

说明:DomSanitizer

  作用

  DomSanitizer有助于防止跨站点脚本安全漏洞(XSS),通过清除值以便在不同的DOM上下文中安全使用。

  为什么会需要使用DomSanitizer

  Angular4中默认将所有输入值视为不受信任。当我们通过 property,attribute,样式,类绑定或插值等方式,将一个值从模板中插入到DOM中时,Angular4会自帮我们清除和转义不受信任的值。