You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular响应式表单的富文本编辑器中插入预定义文本

富文本编辑器选中位置插入预定义文本的解决方案

问题说明

需要将预定义文本(通过expression参数传入)插入到富文本编辑器的选中位置,而非追加到文本末尾。之前使用patchValue直接拼接文本的方式会导致内容被加到末尾且自动换行:

  • 插入前:

This is a selected text: [Spot to put the text]. Neat.

  • 插入后:

This is a selected text: . Neat
[Selected text]

原代码:

onPutWord( expression : any ){
    this.demoForm.get('richTextareaInput')?.patchValue(   
       this.plantillaForm.value.richTextarea + expression;   
    );
}

解决方法

原生textarea/input场景

直接操作DOM获取选中范围,拼接字符串后更新表单值,同时恢复光标位置:

// 推荐用ViewChild获取DOM元素(Angular环境)
import { ViewChild, ElementRef } from '@angular/core';

@ViewChild('richTextareaInput') richTextarea!: ElementRef<HTMLTextAreaElement>;

onPutWord(expression: any) {
  const textarea = this.richTextarea.nativeElement;
  if (!textarea) return;

  const startPos = textarea.selectionStart;
  const endPos = textarea.selectionEnd;
  const currentValue = textarea.value;

  // 拼接新内容:选中前文本 + 插入内容 + 选中后文本
  const newValue = currentValue.substring(0, startPos) + expression + currentValue.substring(endPos);

  // 更新表单控件值
  this.demoForm.get('richTextareaInput')?.setValue(newValue);

  // 恢复光标到插入后的位置
  setTimeout(() => {
    textarea.selectionStart = textarea.selectionEnd = startPos + expression.length;
  }, 0);
}

第三方富文本编辑器场景(如Quill、CKEditor)

直接使用编辑器提供的API插入内容,以Quill为例:

// 假设已初始化Quill实例
private quillInstance: Quill;

onPutWord(expression: any) {
  const range = this.quillInstance.getSelection();
  if (range) {
    // 在选中位置插入文本
    this.quillInstance.insertText(range.index, expression);
    // 同步更新表单值(根据编辑器绑定方式调整)
    this.demoForm.get('richTextareaInput')?.setValue(this.quillInstance.getContents());
  }
}

关键注意事项

  • 优先用ViewChild获取DOM元素,避免getElementById的ID冲突问题
  • 使用setValue更新表单值,语义更明确
  • 恢复光标位置需用setTimeout,确保Angular DOM更新完成后生效

内容的提问来源于stack exchange,提问作者Felipe Antonio Guzmán Anabalon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 09:55:21