Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup CodeMirror 6 with Angular 12

As I'm trying to setup a editor in codemirror v6 with angular but having difficulties in set up as it differs from previous v5.X. Need help in setting up codemirror basic editor with angular. Thank you.

import {EditorState, EditorView, basicSetup} from "@codemirror/basic-setup";
import {javascript} from "@codemirror/lang-javascript";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
  // Define var here...
  title = 'cEditor';
  @ViewChild('editor') editor: any;

  ngOnInit() {
    this.editor = new EditorView({
      state: EditorState.create({
        extensions: [basicSetup, javascript()]
      }),
      parent: document.body
    })
  }
}
like image 775
Arpan Patnaik Avatar asked Oct 12 '25 00:10

Arpan Patnaik


1 Answers

You almost there,

Update import.

import { AfterViewInit, Component, Inject } from '@angular/core';
import { basicSetup} from "codemirror";
import { EditorState } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import { javascript } from "@codemirror/lang-javascript";
import { DOCUMENT } from '@angular/common';

AfterViewInit is preferable to ngOnInit as there is work referencing the element.

And don't forget to declare document at constructor when you set parent with body

constructor(@Inject(DOCUMENT) private document: Document) {}

That's it !!!.


This will help you as It did to me. CodeMirror 5 to 6 Migration Guide

Also you can check this.

  • DEMO: codemirror6 with Angular 12 sample
  • DEMO: codemirror6 with Angular 13 sample

Please make sure as below before start:

  • @codemirror/basic-setup --> npm install [email protected]
  • basicSetup, This extension does not allow customization.
like image 187
jornathan Avatar answered Oct 14 '25 16:10

jornathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!