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

如何在Angular中使用Ace-Editor?配置后编辑器显示异常求助

问题原因

  1. 你启用了ViewEncapsulation.ShadowDom样式隔离,ACE编辑器默认会将自身依赖的样式插入到全局document的<head>标签中,无法穿透ShadowDom作用到组件内部的编辑器DOM上,导致布局样式缺失,编辑器无法正常撑开。
  2. basePath配置错误:当前配置的路径指向了完整的ace.js文件,正确的basePath只需要配置到src-noconflict目录即可。
  3. 编辑器初始化完成后未主动触发尺寸适配,部分场景下DOM渲染时序差会导致编辑器无法读取到容器的宽高值。

解决步骤

  1. 修正basePath配置:
    把原来的basePath配置改为如下内容,删除末尾的ace.js文件名:
ace.config.set(
   'basePath',
   "https://ace.c9.io/build/src-noconflict/"
);
  1. 手动向ShadowDom注入ACE样式:
    在初始化编辑器前,将ACE所需的基础样式插入到当前组件的ShadowRoot中,解决样式隔离导致的样式缺失问题,完整修改后的ngAfterViewInit代码如下:
ngAfterViewInit(): void {
   ace.config.set("fontSize", "14px");
   ace.config.set(
      'basePath',
      "https://ace.c9.io/build/src-noconflict/"
   );

   // 新增:向ShadowRoot注入ACE基础样式
   const shadowRoot = this.editor.nativeElement.getRootNode() as ShadowRoot;
   const aceStyle = document.createElement('style');
   // 可根据需求补充完整的ACE编辑器样式
   aceStyle.textContent = `
   .ace_editor {
     position: relative !important;
     overflow: hidden;
     font: 14px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
     width: 100% !important;
     height: 100% !important;
   }
   .ace_scroller, .ace_content {
     position: absolute;
     inset: 0;
   }
   `;
   shadowRoot.appendChild(aceStyle);

   const aceEditor = ace.edit(this.editor.nativeElement);
   aceEditor.setTheme("ace/theme/monokai");
   aceEditor.session.setMode("ace/mode/html");
   // 新增:主动触发尺寸适配
   aceEditor.resize();
   
   aceEditor.on("change", () => {
      console.log(aceEditor.getValue());
   });
}
  1. 可选方案:如果没有强制要求保留ShadowDom隔离,直接把@Component配置里的encapsulation : ViewEncapsulation.ShadowDom删除即可,恢复默认样式模式后ACE的全局样式就能正常作用到编辑器上。

内容的提问来源于stack exchange,提问作者Omar Al Masalma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:36:03