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

Angular中SurveyJS+QuillJS多富文本框计数器关联异常求助

解决SurveyJS Creator中Quill富文本计数器关联多个编辑器的问题

问题

在Angular中集成SurveyJS Creator与QuillJS后,为富文本编辑器添加了自定义字符计数模块,但添加多个富文本字段时,所有编辑器的输入都会更新第一个计数器,所有框绑定到同一个计数器,需要让每个字段对应独立的计数器。

原因分析

计数器模块中使用document.querySelector('.counter')获取容器,该方法仅返回匹配选择器的第一个元素,导致所有Quill实例都绑定到页面中的第一个.counter容器,从而出现所有编辑器共用一个计数器的问题。

解决方案

1. 为每个Quill组件生成唯一计数器ID

修改quill.component.ts,利用Survey问题的唯一name属性生成专属ID:

@Component({
  selector: 'quill',
  templateUrl: './quill.component.html',
  styleUrls: ['./quill.component.scss'],
})
export class QuillComponent extends QuestionAngular<QuestionQuillModel> {
  // 生成唯一计数器ID
  public get counterId(): string {
    return `counter-${this.model.name}`;
  }

  public get content() {
    return this.model.value;
  }
  public set content(val: string) {
    this.model.value = val;
  }
}

2. 修改模板绑定唯一ID与独立计数器配置

更新quill.component.html,为计数器容器设置唯一ID,并给当前Quill编辑器传入专属的计数器配置:

<div class="editor-counter">
  <quill-editor
    class="q-editor"
    [readOnly]="model.isReadOnly"
    [(ngModel)]="content"
    [styles]="{ height: model.height, width: model.width }"
    <!-- 传入独立的counter模块配置,指定当前组件的计数器ID -->
    [modules]="{ counter: { container: '#' + counterId, unit: 'char' } }"
  >
  </quill-editor>
  <!-- 绑定唯一ID到计数器容器 -->
  <div [id]="counterId" class="counter"></div>
</div>

3. 移除全局计数器配置(避免冲突)

修改App.module.ts中的Quill全局配置,删除原来的通用counter模块配置,改为由每个组件单独传入:

QuillModule.forRoot({
  modules: {
    toolbar: [
      [{ header: [1, 2, 3, false] }],
      ['bold', 'italic', 'underline', 'link'],
      [{ list: 'ordered' }, { list: 'bullet' }],
      ['clean'],
    ],
    // 删除全局counter配置
    // counter: {
    //   container: '.counter',
    //   unit: 'char',
    // },
  },
  customModules: [
    {
      implementation: Counter,
      path: 'modules/counter',
    },
  ],
}),

4. 验证计数器模块逻辑

counter.ts无需修改,现在每个Quill实例会传入专属的容器ID,document.querySelector(this.options.container)会精准定位到当前编辑器对应的计数器容器,实现独立更新。

效果

添加多个富文本字段后,每个字段的计数器会独立响应自身的输入内容,不再出现共用计数器的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 11:17:34