Angular解析html标签

在angular中使用innerHtml给标签赋值时,报错:Angular: How to Deal With the 'Sanitizing HTML Stripped Some Content';查资料发现,原来是angular出于安全原因,会将innerhtml内的标签过滤掉,所以渲染失败。最后使用angular的管道解决问题,至于管道的详细介绍,大家可以自行查阅资料。

下面记录一下业务需求实现步骤

  • 需求:要做一个消息搜索功能,将搜索词在当前消息中高亮显示。
  • 思路:
    1、将搜索词替换为带标签html元素;
    2、使用innerhtml方法将替换后的内容赋值给标签。

最终效果图:


消息搜索.png
  • 实现步骤
    1、在utils目录下新建一个nosanitizerpipe.ts文件;文件内容如下:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({ name: 'noSanitize' })  //noSanitize是在html中使用管道时的名称
export class NoSanitizePipe implements PipeTransform {
  constructor(private domSanitizer: DomSanitizer) { }

  transform(html: string): SafeHtml {
    return this.domSanitizer.bypassSecurityTrustHtml(html);
  }
}
目录结构.png

2、在app.module.ts文件中引用;

import { NoSanitizePipe } from '../app/utils/nosanitizerpipe';

//在declarations中声明
@NgModule({
  declarations: [
    ...,
    NoSanitizePipe
  ]
})

3、在ts文件中处理消息(此步骤为我的项目需求,可不参考);

//this.msgValue为搜索的值,item.content.content为当前这条消息内容
//消息为(例):去看房间有正规的报价单吗?
//处理为:去看房间有正规的报价单<span style="color:red;">吗</span>?
item.content.content = (item.content.content).split(this.msgValue).join(`<span style="color:red;">${this.msgValue}</span>`);

4、在HTML中使用。

<p [innerHTML]="item.content.content | noSanitize"></p>

参考地址:https://careydevelopment.us/blog/angular-how-to-deal-with-the-sanitizing-html-stripped-some-content-issue

至此,问题解决,特此记录!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容