zoukankan      html  css  js  c++  java
  • angular中绑定的innerHtml内部样式不起作用的问题

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

    如:

    listItem = "测试<span style='color:red'>红色</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会自帮我们清除和转义不受信任的值。

  • 相关阅读:
    C# 管理IIS7(转)
    KeyDown,KeyPress和KeyUp详解(转)
    C#中事件的声明与使用
    在类中使用SERVER
    什么是强类型,强类型集合
    配置sql server 2000以允许远程访问
    如何使textbox只能输入数字和小数点
    在BUTTON中触发GRIDVIEW的方法
    多个GRIDVIEW同时导入到一个EXCEL文件中
    ajax3.5的BUG
  • 原文地址:https://www.cnblogs.com/boreguo/p/10243039.html
Copyright © 2011-2022 走看看