scttcper / ngx-codemirror

Codemirror Wrapper for Angular
https://ngx-codemirror.vercel.app
MIT License
282 stars 47 forks source link

Problem getting CodeMirror instance with Angular 13 #310

Closed foorschtbar closed 2 years ago

foorschtbar commented 2 years ago

Hi,

i can't get access to the CodeMirror instance with Angular 13. Unfortunately, I'm stuck and can't find the error. I have looked at these posts and also tried - unfortunately without success

My code to get the instance is:

app.component.html

<ngx-codemirror #codeMirror [...]></ngx-codemirror>

app.component.ts

import { CodemirrorComponent } from '@ctrl/ngx-codemirror';
[...]
@ViewChild('codeMirror') codeMirrorCmpt: CodemirrorComponent;
[...]
 ngAfterViewInit() {
    console.log("this.codeMirrorCmpt", this.codeMirrorCmpt);
    console.log("this.codeMirrorCmpt.codeMirror", this.codeMirrorCmpt.codeMirror); // --> undefined
  }

I always get undefined for this.codeMirrorCmpt.codeMirror, although the this.codeMirrorCmptobject had a codeMirror-Node.

Here is also a MWE: https://stackblitz.com/edit/angular-ivy-6byrzp

Regards, Fabian

wuboy0307 commented 2 years ago

I met the same problem. But if I move the line to a function which will call later. It works.

  ngAfterViewInit() {
    this.changeDetectorRef.detectChanges();
  }

  validateFormula(e) {
    this.codeMirrorEditor = this.editor.codeMirror;  // here
  }
foorschtbar commented 2 years ago

Thank u @wuboy0307! The later was the key:

const timer = setInterval(() => {
  if (this.codeMirrorCmpt.codeMirror !== undefined) {
    console.log("now working!", this.codeMirrorCmpt.codeMirror)
    [...]
    clearInterval(timer);
  } else {
    console.log("nope :(")
  }
}, 500)