I am trying to create a custom HTML element using Web Components that will contain an instance of Ace Editor. My attempted solution is the following
customElements.define("test-editor", class extends HTMLElement {
constructor() {
super();
const editorContainer = document.createElement("div");
editorContainer.setAttribute("id", "editor_container");
const root = this.attachShadow({mode: "open"});
root.appendChild(editorContainer);
}
connectedCallback() {
ace.edit("editor_container");
}
});
I then try to use this custom element in the following HTML (custom_element.js contains the above)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
html, body, #editor_container {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<test-editor></test-editor>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
<script src="custom_element.js"></script>
</body>
</html>
When I load this page in either Chrome or Firefox, I get the following error in the console
Uncaught Error: ace.edit can't find div #editor_container
at Object.t.edit (ace.js:1)
at HTMLElement.connectedCallback (custom_element.js:17)
at custom_element.js:3
Is there any way I can embed an instance of Ace Editor in a custom element?
There is a demo of using shadow-dom in ace repository
The important part is to pass dom element instead of a string to the edit method And to call editor.renderer.attachToShadowRoot