在Angular 11/12的ngx-editor中添加光标位置填空功能的求助
在Angular 11/12的ngx-editor中实现光标位置插入填空标记
核心思路
ngx-editor基于ProseMirror实现,需利用ProseMirror的选区与节点操作API,在当前光标位置插入自定义的填空HTML节点。
实现步骤
1. 组件模板配置
在模板中引入ngx-editor组件,并添加触发插入操作的按钮:
<ngx-editor #editor [editor]="editorInstance" [ngModel]="content"></ngx-editor> <button (click)="insertBlank()">插入填空</button>
2. 组件类逻辑实现
导入必要依赖,通过@ViewChild获取编辑器实例,编写插入填空的核心方法:
import { Component, ViewChild, OnDestroy } from '@angular/core'; import { Editor, NgxEditorComponent } from 'ngx-editor'; import { Node as ProseNode } from 'prosemirror-model'; import { TextSelection } from 'prosemirror-state'; @Component({ selector: 'app-editor-demo', templateUrl: './editor-demo.component.html', styleUrls: ['./editor-demo.component.css'] }) export class EditorDemoComponent implements OnDestroy { @ViewChild('editor') editorComponent!: NgxEditorComponent; editorInstance: Editor; content = ''; constructor() { // 初始化编辑器实例 this.editorInstance = new Editor(); } insertBlank(): void { const editor = this.editorComponent.editor; if (!editor) return; const state = editor.state; const schema = state.schema; // 创建填空节点:使用span标签,设置不可编辑属性与样式类 const blankNode = schema.node('span', { class: 'blank', contenteditable: 'false' }, [schema.text('____')]); // 校验当前选区是否为文本选区 const selection = state.selection; if (!(selection instanceof TextSelection)) return; // 创建事务,插入填空节点 const tr = state.tr.insert(selection.$from.pos, blankNode); // 将光标移动到填空节点之后,方便后续编辑 tr.setSelection(TextSelection.create(tr.doc, selection.$from.pos + blankNode.nodeSize)); // 提交事务,更新编辑器内容 editor.dispatch(tr); } ngOnDestroy(): void { // 销毁编辑器实例,避免内存泄漏 this.editorInstance.destroy(); } }
3. 添加填空样式
在组件样式文件中定义填空的视觉样式:
.blank { display: inline-block; border-bottom: 2px solid #000; min-width: 80px; margin: 0 4px; color: transparent; user-select: none; }
关键说明
- 版本适配:确保ngx-editor版本与Angular版本匹配,Angular 11对应ngx-editor v13.x,Angular 12对应v14.x
- 不可编辑控制:通过
contenteditable="false"和user-select: none确保填空区域无法被用户修改 - 光标优化:插入节点后自动将光标移至填空后方,提升编辑流畅度
- 自定义扩展:可根据需求修改填空节点的文本内容、样式宽度或标签类型(如使用
div实现块级填空)
内容的提问来源于stack exchange,提问作者debugmode
相关产品推荐
相关产品推荐

