如何从CKEditor获取数据?调用getData函数报错求助
解决CKEditor调用
getData()报“not a function”的问题 你这是把CKEditor的构建器类和编辑器实例搞混啦,这才导致了这个报错。我来一步步帮你理清问题并解决:
问题根源
你一开始把ClassicEditor(这是CKEditor的构建器类)赋值给了public Editor,但后面又在create()的回调里把创建出来的编辑器实例赋值给了this.Editor——这直接把原本的构建器覆盖了。更关键的是:Angular版的CKEditor组件会自动帮你创建编辑器实例,你手动调用ClassicEditor.create()完全是多余的,反而造成了变量混乱,最后调用this.Editor.getData()时,这个this.Editor根本不是正确的编辑器实例。
正确的实现方式
我们要通过Angular CKEditor组件的ready事件来获取编辑器实例,同时保留构建器类的引用给组件绑定使用:
1. TypeScript代码调整
import { Component, ViewChild } from '@angular/core'; import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import { CKEditorComponent } from '@ckeditor/ckeditor5-angular'; @Component({ // 你的组件元数据(selector、templateUrl等) }) export class YourComponent { // 保留构建器类的引用,用于模板的[editor]绑定 public Editor = ClassicEditor; public editorData = ''; // 声明变量存储编辑器实例 private editorInstance: any; // 也可以用ViewChild直接获取组件实例 @ViewChild('editorComponent') editorComponent!: CKEditorComponent; // 通过组件的ready事件获取实例 onEditorReady(editor: any) { this.editorInstance = editor; // 这里可以做一些实例初始化的自定义操作 } // 封装获取编辑器内容的方法 getEditorContent() { if (this.editorInstance) { const content = this.editorInstance.getData(); console.log('编辑器内容:', content); return content; } // 也可以通过ViewChild获取组件的editor实例调用方法 // const content = this.editorComponent.editor?.getData(); } }
2. HTML模板调整
<!-- 添加#editorComponent标记方便ViewChild获取,同时绑定ready事件 --> <ckeditor #editorComponent [editor]="Editor" [data]="editorData" (ready)="onEditorReady($event)" ></ckeditor> <!-- 测试用的按钮,点击获取内容 --> <button (click)="getEditorContent()">获取编辑器内容</button>
关键注意点
[editor]="Editor"绑定的必须是CKEditor的构建器类(比如ClassicEditor),绝对不能是实例。- 不要手动调用
ClassicEditor.create(),Angular组件会自动处理DOM元素和实例创建,手动创建会导致重复实例,还会和组件管理的实例冲突。 - 通过
(ready)事件或者ViewChild获取到的实例,才是正确的、可以调用getData()的对象。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

