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会自帮我们清除和转义不受信任的值。

  • 相关阅读:
    SGU 187 Twist and whirl
    伸展树---初步学习
    poj 2503 Babelfish
    sublime 3 phpfmt配置(大括号对齐)
    Linux Shell 错误: $' ': command not found错误解决
    redis 使用场景
    wireshake tcp 三次握手详解
    ip地址和子网掩码
    phpstorm 远程调式 php
    win10,ubuntu时间不对问题
  • 原文地址:https://www.cnblogs.com/boreguo/p/10243039.html
Copyright © 2011-2022 走看看