From @ctrl/ngx-codemirror library, how to get the codeMirror instance with typeScript and angular 5
Asked Answered
H

2

6

I am using the code-mirror wrapper from https://github.com/TypeCtrl/ngx-codemirror

I am trying to get the instance of Codemirror or the Editor to edit some actions but I am not able to get the instance.

related question: Get CodeMirror instance

I need to add a text in the current cursor position on click of a button, thus need the CodeMirror APIs.

Hesper answered 1/6, 2018 at 11:11 Comment(3)
what did you try already? Did you try using tplRef and ViewChild?Nikaniki
tried viewchild and document.getElementByClassName('CodeMirror') in first case its a ElementRef which cant be assigned to Editor in the second case its Element and this also cant be assigned to Editor instanceHesper
Hi @TanmoyBhattacharjee I have a similar problem, I have opened an issue in the ngx-codemirror repo FYI: github.com/TypeCtrl/ngx-codemirror/issues/109Plowboy
H
8

I have solved this. Follow the below steps to get the instance:

import * as CodeMirror from 'codemirror';

Tag your code mirror instance in your html file:

    <ngx-codemirror #codeeditor
                [(ngModel)]="somemodel"
                [options]="someoptions"
                [autoFocus]=true
                (change)="callBackFunc()"
                (cursorActivity)="functionCall()">
</ngx-codemirror>

Read the instance with view-child

@ViewChild('codeeditor') private codeEditor;

Then you can get the editor object it in the relevant function:

const editor = this.codeEditor.codeMirror;
const doc = editor.getDoc();

Make sure you do not use it in the ngOnInit(), instead use it in ngAfterViewInit() with the setTimeOut() as the editor will be available for use only after the view loads fully.

Hesper answered 21/8, 2018 at 6:20 Comment(1)
Avoid using setTimeout() for deferring function execution as you don't know, how much time will loading take.Ruthenious
T
0

I used the accepted answer for years but after updating to the latest version of ngx-codeMirror(7.0.0), the accepted answer stopped working for me. The codeMirrorComponent.codeMirror was still being reported as undefined in the AfterViewInit method.

Now though, there is a convenient eventEmitter for codeMirrorLoaded that you can use to avoid any race conditions with the setup.

<ngx-codemirror ...
      (codeMirrorLoaded)="setCodeMirrorEvents($event)">
    </ngx-codemirror>

Then you can grab the instance like this

setCodeMirrorEvents(editor: CodemirrorComponent){
    const codeMirror = editor.codeMirror; //get editor from component

  }
Tumescent answered 8/3, 2024 at 17:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.