您现在的位置是:网站首页> 编程资料编程资料
monaco editor在Angular的使用详解_AngularJS_
2023-05-24
262人已围观
简介 monaco editor在Angular的使用详解_AngularJS_
正文
本篇文章主要记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用
安装依赖
在 angular12 及之前你可以选择
- monaco-editor
- ngx-monaco-editor
这是没有问题的 但是如果你使用了更高版本的 angular 在使用 npm 安装 ngx-monaco-editor 时 会报错
因为原作者似乎已经停止了对这个库的维护 最终的支持停留在了 angular12 版本

当然 你选择可以选择正如提示那样 用 --force 或者 --legacy-peer-deps 来解决问题
但是为了 消除/避免 隐藏的一些问题 我在原作者的基础上将框架的 angular 支持提升到了 14 并且会一直更新
@rickzhou/ngx-monaco-editor
github github.com/rick-chou/n…
npm www.npmjs.com/package/@ri…
当然 你也可以选择将作者的源代码移入自己的本地代码中 这也是完全没有问题的
- base-editor.ts 引入 monaco-editor
- config.ts
- diff-editor.component.ts
- editor.component.ts
- editor.module.ts
- types.ts

你只需要移动 lib 目录下的六个文件 然后把它们当成自己项目中的一个 module 去使用就好了
使用
其实所有的 api 都可以在 editor.api.d.ts 这个文件中找到
// 在这个editor下就可以找到所有TS类型 import { editor } from 'monaco-editor'; 下面记录一下常用的
- 设置
// 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, }; - 获取editor实例
public initViewEditor(editor: editor.ICodeEditor): void { // 这个editor就是实例 // 下面方法中的editor就是这里的editor this.editor = editor }
- 获取当前光标位置
editor.getPosition()
- 获取当前鼠标选中的文本
editor.getModel().getValueInRange(editor.getSelection());
- 修改光标位置
editor.setPosition({ column: 1, lineNumber: 1, }); - 滚动指定行到可视区中间
editor.revealLineInCenter(1);
- 绑定事件
editor.onMouseDown(event => { // do something }); editor.onKeyDown(event => { // do something }); - 保存/恢复快照
const snapshot = editor.saveViewState(); editor.restoreViewState(snapshot);
- 阻止某个事件
// 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(); } });以上就是monaco editor在Angular的使用详解的详细内容,更多关于Angular使用monaco editor的资料请关注其它相关文章!
相关内容
- 使用uniapp实现发布朋友圈功能_javascript技巧_
- React跨端动态化之从JS引擎到RN落地详解_React_
- React中实现插槽效果的方案详解_React_
- node+koa+canvas绘制出货单、收据票据的方法_node.js_
- vue3组合式api实现v-lazy图片懒加载的方法实例_vue.js_
- 基于Element-Ui封装公共表格组件的详细图文步骤_vue.js_
- mini webpack打包基础解决包缓存和环依赖_JavaScript_
- Webpack 模块加载动态引入机制源码示例解析_javascript技巧_
- Zod进行TypeScript类型验证使用详解_JavaScript_
- vue3 setup语法糖各种语法新特性的使用方法(vue3+vite+pinia)_vue.js_
