【问题标题】:From @ctrl/ngx-codemirror library, how to get the codeMirror instance with typeScript and angular 5从@ctrl/ngx-codemirror 库中,如何使用 typeScript 和 angular 5 获取 codeMirror 实例
【发布时间】:2018-06-01 11:11:36
【问题描述】:

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

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

相关问题:Get CodeMirror instance

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

【问题讨论】:

  • 你已经尝试了什么?您是否尝试过使用 tplRef 和 ViewChild?
  • 在第一种情况下尝试了 viewchild 和 document.getElementByClassName('CodeMirror') 它的 ElementRef 不能分配给 Editor 在第二种情况下它的 Element 并且这也不能分配给 Editor 实例
  • 嗨@TanmoyBhattacharjee 我有一个类似的问题,我在ngx-codemirror repo 中打开了一个问题仅供参考:github.com/TypeCtrl/ngx-codemirror/issues/109

标签: typescript angular5 codemirror


【解决方案1】:

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

import * as CodeMirror from 'codemirror';

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

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

使用 view-child 读取实例

@ViewChild('codeeditor') private codeEditor;

然后就可以在相关函数中获取editor对象了:

const editor = this.codeEditor.codeMirror;
const doc = editor.getDoc();

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

【讨论】:

  • 避免使用 setTimeout() 来延迟函数执行,因为您不知道加载需要多长时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多