从@ctrl/ngx-codemirror 库中,如何使用 typeScript 和 angular 5 获取 codeMirror 实例

Tan*_*jee 5 codemirror typescript angular5

我正在使用来自https://github.com/TypeCtrl/ngx-codemirror的代码镜像包装器

我正在尝试获取 Codemirror 的实例或编辑器来编辑某些操作,但我无法获取该实例。

相关问题:获取 CodeMirror 实例

我需要在单击按钮时在当前光标位置添加文本,因此需要 CodeMirror API。

Tan*_*jee 6

我已经解决了这个问题。按照以下步骤获取实例:

import * as CodeMirror from 'codemirror';
Run Code Online (Sandbox Code Playgroud)

在 html 文件中标记代码镜像实例:

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

使用 view-child 读取实例

@ViewChild('codeeditor') private codeEditor;
Run Code Online (Sandbox Code Playgroud)

然后你可以在相关函数中获取编辑器对象:

const editor = this.codeEditor.codeMirror;
const doc = editor.getDoc();
Run Code Online (Sandbox Code Playgroud)

确保你没有在 ngOnInit() 中使用它,而是在 ngAfterViewInit() 中使用它和 setTimeOut() 因为编辑器只有在视图完全加载后才能使用。