Angular 如何去掉HTML标签展示ngx-quill存储的富文本内容?
Angular中展示ngx-quill存储的带HTML标签内容的实现方法
方法1:直接渲染HTML(保留富文本格式)
如果你需要保留ngx-quill编辑时的段落、字体样式等富文本效果,直接使用Angular的[innerHTML]属性绑定即可,浏览器会自动解析HTML标签而不会将其显示为文本。
代码示例
- 组件类中读取localStorage内容:
// 在组件类中 import { Component, OnInit } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Component({ selector: 'app-content-show', templateUrl: './content-show.component.html' }) export class ContentShowComponent implements OnInit { description: string | SafeHtml = ''; constructor(private sanitizer: DomSanitizer) {} ngOnInit(): void { // 从localStorage读取带HTML标签的内容,yourStorageKey替换为你实际的存储键名 const storageData = localStorage.getItem('yourStorageKey'); if (storageData) { const rawHtml = JSON.parse(storageData).description; // 无安全提示可省略sanitizer处理步骤,直接赋值rawHtml即可 this.description = this.sanitizer.bypassSecurityTrustHtml(rawHtml); } } }
- 模板中绑定innerHTML:
<div [innerHTML]="description"></div>
方法2:提取纯文本(完全移除所有HTML标签)
如果你不需要保留任何富文本格式,只需要显示纯文字内容,可以自定义一个Angular管道批量移除所有HTML标签,复用性更高。
代码示例
- 自定义strip-html管道:
// strip-html.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'stripHtml', standalone: true // 非standalone项目可删除该行,在对应模块的declarations中声明管道即可 }) export class StripHtmlPipe implements PipeTransform { transform(value: string): string { if (!value) return ''; // 正则匹配移除所有HTML标签 return value.replace(/<[^>]*>/g, ''); } }
- 模板中直接使用管道:
<div>{{ description | stripHtml }}</div>
注意事项
- 如果存储的HTML内容来自用户公开输入,渲染前建议做XSS漏洞检测,避免恶意脚本注入风险。
- 若需要和ngx-quill编辑器的渲染效果完全一致,可直接引入quill的默认样式文件到项目全局样式中。
内容的提问来源于stack exchange,提问作者Hisywm
相关产品推荐
相关产品推荐

