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

  • 相关阅读:
    ELK安装(ubuntu)
    Ubuntu18.04上安装java
    .net core跨平台的文件路径
    缺少vim
    docker进入容器
    docker删除名字为none的imgae
    Ubuntu18.04上安装Docker-Compose
    Java类的反射
    Java常用类(二) Scanner类和大数类
    Java常用类(一)Math类和Random类
  • 原文地址:https://www.cnblogs.com/boreguo/p/10243039.html
Copyright © 2011-2022 走看看