You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用@ViewChild获取innerHTML时如何保留空格与换行?

如何保留innerHTML的空格与换行?

我通过templateRef和@ViewChild()装饰器获取元素的innerHTML并展示时,所有空格和换行都消失了,仅显示为一段长文本。尝试用<pre>包裹、添加white-space:pre样式类均无效。

示例代码

component.html

<div>This is HTML</div>
<div [innerText]="code"></div>

<div>This is rendered HTML:</div>
<div #htmlRef>
  <div>
    <span>Hello world</span>
  </div>
</div>

component.ts

export class Component implements AfterViewInit {
  @ViewChild('htmlRef') htmlRef!: ElementRef;
  code!: string | null;

  ngAfterViewInit() {
    this.code = this.htmlRef.nativeElement.innerHTML;
  }
}

实际展示结果

This is HTML
<div _ngcontent-bkp-c29=""><span _ngcontent-bkp-c29="">Hello world</span></div>

期望展示结果

This is HTML
<div _ngcontent-bkp-c29="">
    <span _ngcontent-bkp-c29="">Hello world</span>
</div>

解决方案

问题核心是浏览器解析DOM后,会自动压缩innerHTML中的空白字符(换行、多余空格等),因此仅靠样式无法恢复原始格式,需要主动格式化获取到的HTML字符串。

方法1:利用浏览器API手动格式化

通过DOMParser和XMLSerializer实现格式化:

ngAfterViewInit() {
  const rawHtml = this.htmlRef.nativeElement.innerHTML;
  const parser = new DOMParser();
  const doc = parser.parseFromString(rawHtml, 'text/html');
  const serializer = new XMLSerializer();
  // 移除序列化后自动添加的<body>标签
  this.code = serializer.serializeToString(doc.body).replace(/<body>|<\/body>/g, '');
}

方法2:使用第三方格式化库(如Prettier)

如果需要更规范的格式化效果,可引入Prettier:

  1. 安装依赖:
npm install prettier --save-dev
  1. 在组件中使用:
import prettier from 'prettier';
import parserHtml from 'prettier/parser-html';

// ...

ngAfterViewInit() {
  const rawHtml = this.htmlRef.nativeElement.innerHTML;
  this.code = prettier.format(rawHtml, {
    parser: 'html',
    plugins: [parserHtml],
    tabWidth: 4, // 自定义缩进空格数
    printWidth: 80
  });
}

展示注意事项

确保用<pre>标签包裹展示区域,并绑定innerText而非innerHTML,这样格式化后的换行和缩进才能正确显示:

<pre [innerText]="code"></pre>

内容的提问来源于stack exchange,提问作者Marc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:17:33