Angular中如何为p-editor组件绑定keyup事件属性
问题原因
- p-editor 是 PrimeNG 封装 Quill 富文本引擎的组件,内部并非原生 textarea 结构,直接给组件绑定
keyup事件无法获取到正确的输入内容,$event.target.value取值会失效。 - 你之前逻辑失效的核心是
valueStatement没有拿到 p-editor 的实时内容,导致下拉选中值拼接后赋值的结果不符合预期。
解决方法
直接使用 p-editor 官方提供的 onTextChange 事件监听内容变化,该事件会覆盖键盘输入、粘贴、工具栏操作等所有内容变更场景,比自行绑定 keyup 兼容性更强。
修改后代码
TS 代码
getValueStatement(event: any) { // 若仅需要纯文本内容,将htmlValue替换为textValue即可 this.valueStatement = event.htmlValue; } getValueCaption(event: any) { // 优先从响应式表单控件直接取当前值,避免依赖外部变量导致的不同步问题 const currentContent = this.formEmailTemplates.controls['template'].value || ''; this.formEmailTemplates.controls['template'].setValue(currentContent + event.label); // 按需同步更新valueStatement this.valueStatement = currentContent + event.label; }
HTML 代码
<p-dropdown [options]="captions" [(ngModel)]="selectedCaption" placeholder="Select a Caption" optionLabel="label" [showClear]="true" (onChange)="getValueCaption($event.value)"> </p-dropdown> <p-editor formControlName="template" [style]="{'height':'300px', 'width':'869px'}" (onTextChange)="getValueStatement($event)"> </p-editor>
注:原p-editor上绑定的pInputTextarea、type="text"为无效属性,已删除
扩展提示
如果需要插入带自定义格式的内容到富文本中,可以通过组件实例调用Quill原生API操作:
// 组件头部引入 import { Editor } from 'primeng/editor'; // 组件类中声明 @ViewChild(Editor) editor!: Editor; // 插入内容时调用,示例为在末尾追加纯文本 this.editor.quill.insertText(this.editor.quill.getLength(), event.label);
内容的提问来源于stack exchange,提问作者Oryza
相关产品推荐
相关产品推荐

