angular [innerHtml]=“contentxq“ 不显示行内样式style pipe 返回值去掉html标签安全文本

本文介绍了在Angular应用中如何使用管道处理从后台获取的HTML数据,通过`DomSanitizer`确保安全显示,并创建自定义管道去除HTML标签,展示纯文本内容。详细步骤包括创建`html`和`text`管道,以及在不同模块中引入和使用这些管道。
摘要由CSDN通过智能技术生成

问题描述

使用百度编辑器Ueditor,后台能返回正确的数据格式
在这里插入图片描述
使用[innerHTML]展示数据后div内没有行内样式
在这里插入图片描述

解决办法

在需要的地方新建管道

ng g pipe pipes/html

在这里插入图片描述
htmlpie管道代码

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
    name: 'html'
})
export class HtmlPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) {}

    transform(style: any) {
        return this.sanitizer.bypassSecurityTrustHtml(style);
    }

}

默认新建的管道会在core.module.ts中自动添加

import { HtmlPipe } from './pipes/html.pipe'
@NgModule({
  declarations: [
     HtmlPipe,
  ],

在html中的使用

<div [innerHTML]="contentxq | html"></div>

其他模块引用

比如在home模块中引用,在home.module.ts中添加如下内容

import { CoreModule } from '../../core/core.module';
@NgModule({
  imports: [
  CoreModule,
  ]

引用后就可以在html中正常使用

这是另一个功能

去掉接口返回数据中的html标签

要实现的效果:
将msgContent中的html标签去掉只展示文字
在这里插入图片描述
1、新建text.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'text'})
export class textPipe implements PipeTransform {
    transform(text: any): any {
    	//js方法,去掉所有html标签
        return text.replace(/<[^>]+>/g,'')
    }
}

2、在module文件中引入管道

import { textPipe} from './service/text.pipe'
@NgModule({
  declarations: [textPipe],
  }

4、在html中使用管道

<div class="wd-message" innerHtml="{{ data?.msgBody.msgContent | text }}"></div>

5、实现效果
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值