如何在Angular 12中配置CodeMirror 6基础编辑器?
Angular 12 配置 CodeMirror v6 基础编辑器解决方案
问题描述
尝试在Angular 12中配置CodeMirror v6编辑器,由于与旧版本v5.X差异较大,配置遇到困难,当前代码如下:
import {EditorState, EditorView, basicSetup} from "@codemirror/basic-setup"; import {javascript} from "@codemirror/lang-javascript"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { // Define var here... title = 'cEditor'; @ViewChild('editor') editor: any; ngOnInit() { this.editor = new EditorView({ state: EditorState.create({ extensions: [basicSetup, javascript()] }), parent: document.body }) } }
解决方案
你的代码存在两个核心问题:未正确关联组件模板中的DOM容器、使用了错误的生命周期钩子。以下是完整的正确配置步骤:
- 安装依赖
确保已安装所需的CodeMirror包:
npm install @codemirror/basic-setup @codemirror/lang-javascript
- 修改组件模板
在app.component.html中添加编辑器的容器元素,通过#editor标记供组件获取:
<div #editor class="editor-container"></div>
- 修正组件逻辑
使用ngAfterViewInit钩子(视图初始化后执行),将EditorView挂载到指定的DOM容器中,并优化类型定义:
import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core'; import { EditorState, EditorView, basicSetup } from "@codemirror/basic-setup"; import { javascript } from "@codemirror/lang-javascript"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements AfterViewInit { title = 'cEditor'; @ViewChild('editor') editorRef!: ElementRef<HTMLElement>; editorView?: EditorView; ngAfterViewInit(): void { this.editorView = new EditorView({ state: EditorState.create({ extensions: [ basicSetup, javascript() ], // 可设置初始内容 doc: "// 在这里编写JavaScript代码" }), parent: this.editorRef.nativeElement }); } }
- 引入样式
在app.component.css中导入CodeMirror的基础样式,确保编辑器正常显示:
@import "@codemirror/basic-setup/style.css"; .editor-container { height: 400px; border: 1px solid #ddd; }
关键说明
- 生命周期钩子选择:
ngOnInit执行时,组件视图尚未完全初始化,@ViewChild无法获取到DOM元素,必须使用ngAfterViewInit。 - 容器挂载:将EditorView的
parent指定为组件内的DOM容器,而非document.body,避免编辑器脱离组件上下文。 - 类型安全:将
editorRef的类型定义为ElementRef<HTMLElement>,替代any提升代码可维护性。
内容的提问来源于stack exchange,提问作者Arpan Patnaik
相关产品推荐
相关产品推荐

