Search code examples
angularweb-componentace-editor

How can I use Ace-Editor in Angular?


I'm developing a web component using Angular 12 and I am using ACE editor. I followed a tutorial (link below) step by step but ended up with weird results. I ended up having the editor in one thin column -in grey- and it's not connected to div. (https://blog.shhdharmen.me/how-to-setup-ace-editor-in-angular)

Any clue why this happened?

seite.html

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

component.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());
     });
  }
}

Solution

  • This happens because of shadow dom encapsulation hiding global styles from ace

    Add

     aceEditor.renderer.attachToShadowRoot()
    

    to let editor know that it is in shadow dom element and needs to add extra styles to it.

    Also basepath should not contain ace.js

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