前端:Angular框架与Ionic框架集成Html翻译pipe(管道)

在前端开发的时候经常会遇到页面显示的内容有HTML标记。默认是没有经过翻译的。集成翻译管道就可以正常显示内容。由于Angular与ionic集成的方法有点不,所以分开写。

一、Angular框架集成pipe

1、新建一个管道

新建命令:ng g pipe pipe/tohtml
tohtml.pipe.ts文件代码:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'tohtml' //使用名称
})
export class TohtmlPipe implements PipeTransform {
//构造方法中加入DomSanitizer
  constructor(private _sanitizer: DomSanitizer){}
  transform(html: any, args?: any): any {
  //获取到HTML内容,对html进行转换
    return this._sanitizer.bypassSecurityTrustHtml(html);
  }
}

2、在使用的地方进行引用

 <div [innerHTML]="n.content | tohtml">

二、Ionic框架集成pipe

1、新建一个管道

新建命令:ionic g pipe pipes/html
html.pipe.ts文件代码
import { Pipe, PipeTransform } from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';

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

  //将DomSanitizer添加到构造方法中
    constructor(private _sanitizer: DomSanitizer){}
    transform(value: any, ...args: any[]): any {
      //这里返回的一个html内容,将value进行转换
        return this._sanitizer.bypassSecurityTrustHtml(value);
    }
}

2、集成module,进行模块化

新建命令:ionic g module pipes/pipes
pipes.module.ts文件代码:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {HtmlPipe} from "../html.pipe";


@NgModule({
  declarations: [HtmlPipe],
  imports: [
    CommonModule
  ],
    exports:[HtmlPipe]
})
export class PipesModule { }

3、去掉app.module.ts文件的declarations版块的HtmlPipe声明

image

4、在使用的模块的module里面加上PipesModule

例如在newsdetail.module.ts里面的imports版块加入PipesModule

image

5、HTML部分

<div [innerHTML]="news.content | html"></div>

5、对比效果

image

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值