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
相关产品推荐
相关产品推荐

