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

ngx-quill集成公式模块后输入公式重复显示问题求助

解决ngx-quill公式重复显示的问题

问题描述

在ngx-quill编辑器中添加公式功能后,输入公式时会出现重复显示两次的情况,使用的配置代码如下:

modules = {
  toolbar: [      
    [{ header: [1, 2, false] }],
    ['bold', 'italic', 'underline'],
    ['formula'], 
    ['image', 'code-block']
  ]
};

原因分析

这个问题核心是Quill的Formula模块与ngx-quill默认渲染逻辑冲突,或是依赖加载不规范导致公式被双重解析渲染:一次由Quill原生Formula模块处理,另一次由ngx-quill额外触发。此外,重复导入Quill相关模块(如多次导入QuillModule)或依赖版本不一致也会引发该问题。

解决方案

1. 规范依赖安装与模块导入

首先确保依赖安装完整:

npm install quill quill-formula ngx-quill

然后在Angular的根模块中只导入一次QuillModule,并显式启用公式模块:

import { QuillModule } from 'ngx-quill';

@NgModule({
  imports: [
    // 其他业务模块
    QuillModule.forRoot({
      modules: {
        formula: true
      }
    })
  ]
})
export class AppModule { }

2. 调整组件内的Toolbar配置

在组件的modules配置中,必须显式开启formula模块,避免隐式触发重复渲染逻辑:

modules = {
  formula: true, // 显式启用公式模块
  toolbar: [      
    [{ header: [1, 2, false] }],
    ['bold', 'italic', 'underline'],
    ['formula'], 
    ['image', 'code-block']
  ]
};

3. 检查模板中的编辑器实例

确保模板内只存在一个quill-editor组件实例,避免重复初始化导致的渲染异常:

<quill-editor [modules]="modules" [(ngModel)]="content"></quill-editor>

4. 手动移除重复公式节点(兜底方案)

若上述方法无效,可通过监听编辑器的文本变化事件,手动清理重复的公式节点:

import { QuillEditorComponent } from 'ngx-quill';
import { ViewChild, AfterViewInit } from '@angular/core';

@Component({
  // 组件元数据(如selector、templateUrl等)
})
export class YourComponent implements AfterViewInit {
  @ViewChild(QuillEditorComponent) editor!: QuillEditorComponent;
  content = '';
  modules = { /* 你的配置内容 */ };

  ngAfterViewInit() {
    this.editor.quillEditor.on('text-change', () => {
      const formulaElements = this.editor.quillEditor.root.querySelectorAll('.ql-formula');
      if (formulaElements.length > 1) {
        formulaElements[1].remove();
      }
    });
  }
}

验证

完成上述配置后重启应用,在编辑器中插入公式,即可看到公式仅显示一次。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:15:33