Angular and Editor.js integration

Angular and Editor.js integration

When it comes to WYSIWYG text editors, Editor.js comes on top. With its simple to use interface and plugin ecosystem, you can extend the functionality and match your needs. In this article we will explore an approach to integrate core Editor.js library inside Angular project.


Prerequisites

So before we dive into Editor.js setup make sure that you have following things ready

  • Angular project generated using CLI (hint use `ng new editor-js-angular`)
  • VS Code to edit project files
Angular and Editor.js integration

Editor.js dependency

The core library can be installed directly inside Angular project by executing following command

npm install --save @editorjs/editorjs

Editor placeholder

Create a new component inside Angular project using following CLI command

ng g c basic-editor

This should generate a new component with 4 files. Open the auto generated HTML file and replace contents with following

<div #editor></div>

The div tag will be used as a placeholder to place Editor.js. The core library requires an HTML element to be used as a container. Replace contents of app.component.html with

<app-basic-editor></app-basic-editor>

Editor.js editor initialization

Open basic-editor.component.ts file and create a new variable which refers to above div element with ViewChild decorator (refer below code).

@ViewChild('editor', { read: ElementRef })
editorElement: ElementRef;

In addition to above variable, also define another variable to hold the reference of Editor.js instance

private editor: EditorJS;

Now we need to instantiate Editor.js function.

private initializeEditor() {
    this.editor = new EditorJS({
      minHeight: 200,
      holder: this.editorElement.nativeElement
    });
  }

The code initializes Editor.js with minimum height and passes reference of the HTML dom element. The constructor also supports additional properties, but lets focus on booting up basic instance. Save all the files and start Angular project

ng serve -o

If there are no mistakes in your project, you should see Editor.js enabled in your application. Congratulations!!! you just discovered a way to add plain vanilla Editor.js inside Angular project.

Bonus - Access Editor.js document as JSON

While your application is now enabled with Editor.js, you will require access to the data generated for each block. You won't find any method named getValue or value, but we are in luck.

In prior step we created a class level variable editor with type as EditorJS. Simply invoke following code to access the JSON generated by Editor.js

this.editor.save().then(data => {
      console.dir(data);
})