我是靠谱客的博主 悲凉砖头,这篇文章主要介绍浅析angular中怎么使用monaco-editor,现在分享给大家,希望可以做个参考。

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

安装依赖

在 angular12 及之前你可以选择

  • monaco-editor
  • ngx-monaco-editor

这是没有问题的 但是如果你使用了更高版本的 angular 在使用 npm 安装 ngx-monaco-editor 时 会报错。【相关教程推荐:《angularjs视频教程》】

因为原作者似乎已经停止了对这个库的维护 最终的支持停留在了 angular12 版本

1.png

当然 你选择可以选择正如提示那样 用 --force 或者 --legacy-peer-deps 来解决问题

但是为了 消除/避免 隐藏的一些问题 我在原作者的基础上将框架的 angular 支持提升到了 14 并且会一直更新

当然 你也可以选择将作者的源代码移入自己的本地代码中 这也是完全没有问题的

  • base-editor.ts 引入 monaco-editor
  • config.ts
  • diff-editor.component.ts
  • editor.component.ts
  • editor.module.ts
  • types.ts

2.png

你只需要移动 lib 目录下的六个文件 然后把它们当成自己项目中的一个 module 去使用就好了

使用

其实所有的 api 都可以在 editor.api.d.ts 这个文件中找到

复制代码
1
2
// 在这个editor下就可以找到所有TS类型 import { editor } from 'monaco-editor';
登录后复制

下面记录一下常用的

1、设置

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// eg export const READ_EDITOR_OPTIONS: editor.IEditorOptions = { readOnly: true, automaticLayout: false, minimap: { enabled: false, }, renderFinalNewline: false, scrollbar: { vertical: 'visible', }, mouseWheelZoom: true, contextmenu: false, fontSize: 16, scrollBeyondLastLine: false, smoothScrolling: true, cursorWidth: 0, renderValidationDecorations: 'off', colorDecorators: false, hideCursorInOverviewRuler: true, overviewRulerLanes: 0, overviewRulerBorder: false, };
登录后复制

2、获取editor实例

复制代码
1
2
3
4
5
6
7
8
9
10
11
<ngx-monaco-editor [options]="readEditorOptions" [(ngModel)]="originLogVal" (onInit)="initViewEditor($event, false)"> </ngx-monaco-editor> public initViewEditor(editor: editor.ICodeEditor): void { // 这个editor就是实例 // 下面方法中的editor就是这里的editor this.editor = editor }
登录后复制

3、获取当前光标位置

复制代码
1
editor.getPosition()
登录后复制

4、获取当前鼠标选中的文本

复制代码
1
editor.getModel().getValueInRange(editor.getSelection());
登录后复制

5、修改光标位置

复制代码
1
2
3
4
editor.setPosition({ column: 1, lineNumber: 1, });
登录后复制

6、滚动指定行到可视区中间

复制代码
1
editor.revealLineInCenter(1);
登录后复制

7、绑定事件

复制代码
1
2
3
4
5
6
editor.onMouseDown(event => { // do something }); editor.onKeyDown(event => { // do something });
登录后复制

8、保存/恢复快照

复制代码
1
2
const snapshot = editor.saveViewState(); editor.restoreViewState(snapshot);
登录后复制

9、阻止某个事件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// eg 组件默认的搜索快捷键 function isMac() { return /macintosh|mac os x/i.test(navigator.userAgent); } editor.onKeyDown(event => { if ( (isMac() && event.browserEvent.key === 'f' && event.metaKey) || (!isMac() && event.browserEvent.key === 'f' && event.ctrlKey) ) { event.preventDefault(); event.stopPropagation(); } });
登录后复制

最后

以上就是悲凉砖头最近收集整理的关于浅析angular中怎么使用monaco-editor的全部内容,更多相关浅析angular中怎么使用monaco-editor内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(174)

评论列表共有 0 条评论

立即
投稿
返回
顶部