Jayz
Jayz

Reputation: 654

ngx-Codemirror cursor is not working correctly-Angular 8

I have implemented ngX-CodeMirror in my angular project. I have added the code editor inside an angular material modal. It works fine I'm not able to move the cursor so that I can click on any text. I am able to click on some text but not where we intend to.

I have added this issue in stackblitz : Code Mirror Cursor Issue

This is s snippet from my component.html file

<ngx-codemirror
 #codeMirror
 [options]="codeMirrorOptions"
 [(ngModel)]="codeObj">
</ngx-codemirror>

And in component.ts,

import { Component, OnInit, ViewChild, ElementRef, Input } from "@angular/core";
import { CodemirrorComponent } from "@ctrl/ngx-codemirror";

export class CodeEditorComponent implements OnInit {
  @Input()
  configs: any;
  testData: any;

  @ViewChild("textArea") textArea: ElementRef; 

  codeMirrorOptions: any = {
    theme: "idea",
    mode: "application/json",
    lineNumbers: true,
    autoRefresh: true
  };

  codeObj: any;
  constructor() {}

  ngOnInit(): void {
    this.codeObj = JSON.stringify(this.configs, undefined, 2);
  }
}

I'm not sure why this happened or if we need to provide any specific options to see mouse cursor. I have seen a related query for this in codeMirrorDiscussionForum but couldn't find a solution yet.

Please do help me solve this issue by referring the stackblitz link.

Upvotes: 4

Views: 2734

Answers (2)

yurzui
yurzui

Reputation: 214017

Yes, I would also wait till the modal is open because the size of code mirror area is being changed over Angular material animation:

dialog.component.ts

export class ExampleModalComponent implements OnInit {
  opened$ = this.dialogRef.afterOpened().pipe(mapTo(true));

dialog.component.html

<ngx-codemirror *ngIf="opened$ | async else loading"
....


<ng-template #loading>Loading...</ng-template>

Forked Stackblitz

Another solution is to disable animation.

Upvotes: 5

David
David

Reputation: 34435

Refresh codeMirror after the modal is open

modal.component.ts

import { CodemirrorComponent } from "@ctrl/ngx-codemirror";

//get a reference to the component
@ViewChild('codeMirror') private codeEditorCmp: CodemirrorComponent;

ngOnInit()
{
  //..conf and code initialisation 
  setTimeout(() => this.codeEditorCmp.codeMirror.refresh(), 1000); //<= add this

Stackblitz demo

Possible Explanation

I don't know codeMirror, but it probably calculates where the caret will go based on where you clicked. I guess this calculation is based on the current component's dimensions, which may be cached.

Since when your modal component is initialised it does not have its full width/height yet (until the modal is fully open), you can force code mirror to refresh once the modal is open.

Upvotes: 7

Related Questions