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语言作业(心理魔术)
    心理魔术
    作业
    作业
    自定义打包小游戏的build template,接入SDK,
    JavaScript_call,bind,apply的区别
    JavaScript原型链的理解
    学习笔记—前端基础之ES6的数组
    学习笔记 — 前端基础之ES6(2)
    学习笔记 — 前端基础之ES6(1)
  • 原文地址:https://www.cnblogs.com/boreguo/p/10243039.html
Copyright © 2011-2022 走看看