如何在Angular中使用Codemirror
安装
环境:
Angular版本: 13.1.0
node版本: 16.13.0
pnpm: 6.25.1
npm: 8.3.2
命令:
npm install @ctrl/ngx-codemirror codemirror@5
//or
pnpm add @ctrl/ngx-codemirror codemirror@5
引入
在需要使用的codemirror模块文件中引入codemoirror,
// in your NgModule
import { CodemirrorModule } from '@ctrl/ngx-codemirror';
import { FormsModule } from '@angular/forms';
// add to imports
imports: [
BrowserModule,
AppRoutingModule,
RouterModule,
CodemirrorModule,
FormsModule
],
在使用codemirror的模板中引入需要的css文件或者js文件 详细配置文档见: codemirror.net/doc/manual.…
// in your ts
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/markdown/markdown';
// in style.css
@import '~codemirror/lib/codemirror';
@import '~codemirror/theme/material';
使用
// in your component
<ngx-codemirror
[(ngModel)]="content"
[options]="{
mode: 'application/json',
tabSize: 2,
json: true,
readOnly: true,
theme: 'monokai',
showCursorWhenSelecting: true,
autoFocus: true,
extraKeys: { 'Ctrl-Space': 'autocomplete' }
}"
></ngx-codemirror>
显示
效果如下:
code-mirror需要点击一下才能显示如何解决
解决办法: 设置autoRefresh: true
//in your ts
import 'codemirror/mode/dockerfile/dockerfile';
//in your config
options = {
autoRefresh: true,
mode: 'application/json',
tabSize: 2,
json: true,
readOnly: true,
theme: 'monokai',
showCursorWhenSelecting: true,
autoFocus: true,
extraKeys: { 'Ctrl-Space': 'autocomplete' }
};