Search code examples
typescriptangular5codemirror

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


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.


Solution

  • 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.