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

Angular中如何在ngx-quill编辑器为空时禁用点击按钮?

解决ngx-quill编辑器为空时提交按钮禁用问题

实现思路

通过监听编辑器内容变化,判断纯文本内容是否为空,动态控制提交按钮的禁用状态,同时处理提交后的编辑器清空与按钮状态重置。

修改component.ts代码

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

// 组件类内部代码
@ViewChild('editor', { static: false }) editor!: QuillEditorComponent;

public stringMessages: string[] = [];
public isSubmitDisabled = true; // 初始状态禁用按钮

// 监听编辑器内容变化,更新按钮状态
onEditorContentChanged() {
  // 获取编辑器纯文本并去除首尾空白字符
  const plainContent = this.editor.quillEditor.getText().trim();
  // 根据内容是否为空切换按钮禁用状态
  this.isSubmitDisabled = plainContent.length === 0;
}

sendMessage() {
  const content = this.editor.quillEditor.root.innerHTML;
  this.stringMessages.push(content);
  // 清空编辑器内容
  this.editor.quillEditor.setText('');
  // 提交后重置按钮为禁用状态
  this.isSubmitDisabled = true;
}

修改component.html代码

给提交按钮添加[disabled]绑定,并绑定编辑器的contentChanged事件:

<quill-editor customToolbarPosition="bottom" id="quill-id" #editor 
              placeholder="Type your message..." [styles]="toolbarStyle"
              (contentChanged)="onEditorContentChanged()">
  <span class="ql-formats-send">
    <button class="ql-send-button" (click)="sendMessage()" [disabled]="isSubmitDisabled">
      <fa-icon [icon]="faMessage"></fa-icon>
    </button>
  </span>
</quill-editor>

关键说明

  • 使用getText().trim()判断内容是否为空:避免编辑器默认生成的空白标签(如<p><br></p>)被误判为有内容,确保只有真正输入文本时按钮才启用。
  • 提交后清空编辑器并重置按钮状态:保证提交完成后,编辑器回到空状态时按钮自动禁用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:35:41