Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 872
Tanmoy Bhattacharjee Avatar asked Jun 01 '18 11:06

Tanmoy Bhattacharjee


People also ask

How do I create a CodeMirror instance?

// create an instance var editor = CodeMirror. fromTextArea('code'); // store it $('#code'). data('CodeMirrorInstance', editor); // get it var myInstance = $('code'). data('CodeMirrorInstance'); // from here on the API functions are available to 'myInstance' again.

What is NGX CodeMirror?

Starter project for Angular apps that exports to the Angular CLI.

What is CodeMirror CSS?

CodeMirror is a versatile text editor implemented in JavaScript for the browser. It is specialized for editing code, and comes with a number of language modes and addons that implement more advanced editing functionality.


1 Answers

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.

like image 109
Tanmoy Bhattacharjee Avatar answered Nov 15 '22 08:11

Tanmoy Bhattacharjee