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

如何在Angular的Summernote中使用insertText在光标位置插入文本

Angular 8中Summernote光标位置插入API返回文本的解决方案

核心思路

由于API请求是异步操作,需要先保存触发插入时的光标选区,待文本返回后恢复选区再执行插入,确保文本插入到指定位置。

实现步骤及代码示例

1. 模板文件(app.component.html)

<summernote #summernote [(ngModel)]="editorContent"></summernote>
<button (click)="insertApiTextAtCursor()">插入API文本</button>

2. 组件文件(app.component.ts)

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { SummernoteComponent } from 'ngx-summernote';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  @ViewChild('summernote') summernote!: SummernoteComponent;
  editorContent = '';
  private targetCursorRange: any;

  ngAfterViewInit() {
    // 确保编辑器完成初始化
    this.summernote.summernote('focus');
  }

  insertApiTextAtCursor() {
    // 保存当前光标选区
    const editor = this.summernote.summernote('editor');
    this.targetCursorRange = editor.getSelection();

    // 替换为你的实际API请求逻辑
    this.getApiText().then(apiResponseText => {
      // 恢复之前保存的光标位置
      if (this.targetCursorRange) {
        editor.restoreSelection(this.targetCursorRange);
      }

      // 插入纯文本,若需插入HTML可改用editor.pasteHTML()
      this.summernote.summernote('insertText', apiResponseText);
    });
  }

  // 模拟API请求,替换为你的HTTP调用(如HttpClient.get)
  private getApiText(): Promise<string> {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve('API返回的目标插入文本');
      }, 800);
    });
  }
}

关键细节说明

  • 获取编辑器实例:通过ViewChild绑定Summernote组件,调用其内部summernote()方法操作编辑器。
  • 选区保存与恢复:异步请求前用editor.getSelection()记录光标位置,请求完成后用editor.restoreSelection()恢复,避免因异步操作导致光标位置偏移。
  • 插入方式选择:
    • 插入纯文本:使用insertText方法
    • 插入HTML内容:改用editor.pasteHTML('<span class="custom-style">HTML文本</span>')

内容的提问来源于stack exchange,提问作者Gem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:27:19