首页 > 解决方案 > 如何在 Angular 中使用 Ace-Editor?

问题描述

我正在使用 Angular 12 开发一个 Web 组件,并且我正在使用 ACE 编辑器。我一步一步地遵循了一个教程(下面的链接),但结果很奇怪。我最终将编辑器放在一个细列中 - 灰色 - 并且它没有连接到 div。(https://blog.shhdharmen.me/how-to-setup-ace-editor-in-angular

任何线索为什么会这样?

网站.html

<div class="app-ace-editor"
     style="width: 500px;height: 250px;"
     #editor></div>

组件.ts

import { Component, ElementRef, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import * as ace from "ace-builds";

@Component({
  selector: 'app-studentfe',
  templateUrl: './studentfe.component.html',
  styleUrls: ['./studentfe.component.css'],
  encapsulation : ViewEncapsulation.ShadowDom
})

export class StudentfeComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  @ViewChild('editor') private editor: ElementRef<HTMLElement>;

  ngAfterViewInit(): void {
     ace.config.set("fontSize", "14px");
     ace.config.set(
        'basePath',
        "https://ace.c9.io/build/src-noconflict/ace.js"
     );

     const aceEditor = ace.edit(this.editor.nativeElement);
     aceEditor.setTheme("ace/theme/monokai");
     aceEditor.session.setMode("ace/mode/html");
     aceEditor.on("change", () => {
        console.log(aceEditor.getValue());
     });
  }
}

标签: angularweb-componentace-editor

解决方案


发生这种情况是因为 shadow dom 封装对 ace 隐藏了全局样式

添加

 aceEditor.renderer.attachToShadowRoot()

让编辑器知道它在 shadow dom 元素中,需要为其添加额外的样式。

basepath也不应该包含ace.js

ace.config.set('basePath', "https://ace.c9.io/build/src-noconflict/");

推荐阅读