Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How to setup Ace editor in Angular?
Dharmen Shah
Dharmen Shah

Posted on • Originally published atblog.shhdharmen.me

     

How to setup Ace editor in Angular?

In this article, I will show you how to ⚡ quickly setup ✏️Ace editor in 🅰️ Angular without any other 3rd party libraries.

✏️ Ace Editor

Ace is an embeddable code editor written in JavaScript. It matches the features and performance of native editors such as Sublime, Vim and TextMate. It can be easily embedded in any web page and JavaScript application. Ace is maintained as the primary editor forCloud9 IDE and is the successor of the Mozilla Skywriter (Bespin) project.

BothCloud9 IDE andMozilla are actively developing and maintaining Ace.

👨‍💻 Let's talk Coding

📁 Create a workspace

Open up your terminal and:

npm i-g @angular/cling new ace-angular--defaults--minimal
Enter fullscreen modeExit fullscreen mode

👉 Do not use--minimal option in production applications, it creates a workspace without any testing frameworks. You can read more aboutCLI options.

At this point, your folder structure should look like this and it is going to be same till the end:

Folder structure

⏬ Install Ace editor

We will install pre-packaged version of Ace fromnpm:

npm i ace-builds
Enter fullscreen modeExit fullscreen mode

🛠️ Setup editor

One advantage of usingace-builds package directly in Angular is that they already provide support for Typescript. You can check in theirrepo, they have their type definitions files at place:

type definitions files

📄 app.component.ts

Clear all the content of the file and start with below:

import{AfterViewInit,Component,ElementRef,ViewChild}from"@angular/core";// 1️⃣import*asacefrom"ace-builds";// 2️⃣@Component({selector:"app-root",template:`    <div           #editor         ></div>  `,styles:[`      .app-ace-editor {        border: 2px solid #f8f9fa;        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);      }    `,],})exportclassAppComponentimplementsAfterViewInit{// 3️⃣@ViewChild("editor")privateeditor:ElementRef<HTMLElement>;// 4️⃣ngAfterViewInit():void{ace.config.set("fontSize","14px");constaceEditor=ace.edit(this.editor.nativeElement);aceEditor.session.setValue("<h1>Ace Editor works great in Angular!</h1>");}}
Enter fullscreen modeExit fullscreen mode

Let's see what's happening here:

  1. First, we are importingace fromace-builds package.
  2. Then, we are setting HTML template. Note thatheight andwidth are required, otherwise editor won't load. I have also added styling, you can skip that if you want.
  3. After above, we are querying our editor using@ViewChild
  4. i. To access queried child of@ViewChild, we need to usengAfterViewInit life-cycle hook. Becuase view queries are set before the ngAfterViewInit callback is called.

ii. We are setting default font-size of editor to14px. There are lots of configuration options which Ace editor provides, please check themhere

iii. Then, we are attaching Ace editor to our#editor element.

iv. And last, we are setting up the default value. You can check the the how-tos of Ace editor at itshow-to guide.

Let's look at the output:

ace editor in angular output

Congratulations 🎉🎉🎉. You have completed the setup of Ace editor. 👏👏👏.

🔭 Further usage

In real-world scenarios, you would also want to enable syntax highlighting and get the value from editor. Let's see it in action.

🌄 Set theme and syntax highlighting

Inapp.component.ts make below changes:

...ngAfterViewInit():void{ace.config.set("fontSize","14px");constaceEditor=ace.edit(this.editor.nativeElement);aceEditor.session.setValue("<h1>Ace Editor works great in Angular!</h1>");// 🚨 AddedaceEditor.setTheme('ace/theme/twilight');aceEditor.session.setMode('ace/mode/html');}
Enter fullscreen modeExit fullscreen mode

Cool. Let's see the output in the browser:

ace editor in angular output

As you can see, highlighting and syntax aren't enabled. Let's see if there is any error in browser console:

browser console error

Error says:Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver, which means Ace is not able to find relevant files for themes and syntax highlighting.

You see, they have already given a solution, too in the error console. That is to use:ace.config.set('basePath', 'path'). By default ace detects the url for dynamic loading by finding the script node for ace.js. This doesn't work if ace.js is not loaded with a separate script tag, and in this case it is required to set url explicitely. And the url should be pointing to a folder that contains ace nodes.

Thanks tounpkg.com, we can get the needed URL:

https://unpkg.com/ace-builds@1.4.12/src-noconflict
Enter fullscreen modeExit fullscreen mode

Let's update it in our code:

...ngAfterViewInit():void{ace.config.set("fontSize","14px");// 🚨 Addedace.config.set('basePath','https://unpkg.com/ace-builds@1.4.12/src-noconflict');constaceEditor=ace.edit(this.editor.nativeElement);aceEditor.session.setValue("<h1>Ace Editor works great in Angular!</h1>");aceEditor.setTheme('ace/theme/twilight');aceEditor.session.setMode('ace/mode/html');}
Enter fullscreen modeExit fullscreen mode

Check the output:

ace editor output after setting basepath

✍️ Get value from editor

...ngAfterViewInit():void{ace.config.set("fontSize","14px");ace.config.set("basePath","https://unpkg.com/ace-builds@1.4.12/src-noconflict");constaceEditor=ace.edit(this.editor.nativeElement);aceEditor.session.setValue("<h1>Ace Editor works great in Angular!</h1>");aceEditor.setTheme("ace/theme/twilight");aceEditor.session.setMode("ace/mode/html");// 🚨 AddedaceEditor.on("change",()=>{console.log(aceEditor.getValue());});}
Enter fullscreen modeExit fullscreen mode

I think it's clear from the code how to get value 😉. You should check all the events supported by Ace editor. Thanks to Typescript and VS Code, you can see it while editing:

supported events

Let's see the output:

ace editor in action

Cool, with that we are done 👍

The final version ofapp.component.ts looks like below:

import{AfterViewInit,Component,ElementRef,ViewChild}from"@angular/core";import*asacefrom"ace-builds";@Component({selector:"app-root",template:`    <div           #editor         ></div>  `,styles:[`      .app-ace-editor {        border: 2px solid #f8f9fa;        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);      }    `,],})exportclassAppComponentimplementsAfterViewInit{@ViewChild("editor")privateeditor:ElementRef<HTMLElement>;ngAfterViewInit():void{ace.config.set("fontSize","14px");ace.config.set("basePath","https://unpkg.com/ace-builds@1.4.12/src-noconflict");constaceEditor=ace.edit(this.editor.nativeElement);aceEditor.session.setValue("<h1>Ace Editor works great in Angular!</h1>");aceEditor.setTheme("ace/theme/twilight");aceEditor.session.setMode("ace/mode/html");aceEditor.on("change",()=>{console.log(aceEditor.getValue());});}}
Enter fullscreen modeExit fullscreen mode

Conclusion

We saw how we can simply use Ace editor in Angular without any 3rd party library usage.

Code is available at Github repo:shhdharmen/ace-angular

ReadMe Card

Thank You

for reading my article. Let me know your thoughts in the comments section.

I am also available on twitter as@shhdharmen if you want to say hi 👋.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I work on Angular, React, Electron, JavaScript, CSS, SCSS, Bootstrap, NodeJS. Love to contribute to Open-Source Projects.
  • Location
    Ahmedabad
  • Education
    Bechelor of Technology
  • Work
    Sr. Full-Stack Developer at Solvative
  • Joined

More fromDharmen Shah

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp