如何从CKEditor获取数据?

how to get data from CKEditor?

我正在尝试从 CKEditor 获取数据?我正在尝试 getData 函数,但它似乎不起作用。

下面是HTML

<ckeditor [editor]="Editor" id="Editor" [data]="editorData"></ckeditor>

下面是打字稿

import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
public Editor = ClassicEditor;
ClassicEditor.create(document.querySelector('#Editor'), {
      toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote'],
      heading: {
        options: [
          { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
          { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
          { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' }
        ]
      },
    }).then(newEditor => {
        this.Editor= newEditor;

      }).catch(error => {
        console.log(error);
    });

如果我尝试 this.Editor.getData(),我会收到一条错误消息,指出 getData 不是一个函数。

您需要获取对编辑器实例的引用,即 this.Editor.ckeditorInstance.getData()

https://ckeditor.com/docs/ckeditor5/latest/builds/guides/faq.html#how-to-get-the-editor-instance-object-from-the-dom-element

这是完整路径:

1) 安装ckEditor如下:

npm i ng2-ckeditor --save

2) 在index.html:

中添加ckEditor脚本
<script src="https://cdn.ckeditor.com/4.13.0/standard/ckeditor.js"></script>

3) 将 CkEditor 模块添加到 AppModule 中的导入部分,如下所示:

import { CKEditorModule } from 'ng2-ckeditor';

imports:
[
  BrowserModule,
  FormsModule,
  CKEditorModule
],

4) 在组件顶部定义如下行

import { Component, OnInit } from '@angular/core';
declare var CKEDITOR: any;

5) 为你的ckEditor定义一个特定的名称(默认名称是editor1):这里我设置内容

ngOnInit(): void {
 CKEDITOR.on('instanceCreated', function (event, data) {
    var editor = event.editor,
    element = editor.element;
    editor.name = "content"
 });
}

6) 在你的app.component.html中(添加一个ckEditor组件和一键获取数据):

<ckeditor #myEditor [(ngModel)]="ckeditorContent" [config]="{uiColor: '#a4a4a4'}" debounce="500"> </ckeditor> <input type="button" value="Get Data" (click)="getData()" />

现在,如果要获取数据,请使用以下命令:

getData() {
  console.log(CKEDITOR.instances.content.getData());
}

StackBlitz Here.

DEMO(检查浏览器的控制台)

对于 CKEditor Classic:

如果你想获取数据,有两种选择:

1) @ViewChild装饰器

在您的组件中定义一个 @Viewchild

@ViewChild("myEditor", { static: false }) myEditor: any; 

然后在你的 Html:

<ckeditor #myEditor [editor]="editor" [data]="data" [(ngModel)]="data"></ckeditor>

现在,您可以通过以下代码获取数据:

this.myEditor.data

2) 更改事件

在您的组件中导入以下行:

import { ChangeEvent } from "@ckeditor/ckeditor5-angular/ckeditor.component";

在您的组件中定义一个名为 retrieveddata 的变量来存储数据

retrieveddata: string = null;

将以下方法作为 chagneEvent

放入您的组件中
public onChange({ editor }: ChangeEvent) {
 const data = editor.getData();
 this.retrieveddata=data;
}

然后在你的 Html 中:

<ckeditor [editor]="editor" [data]="data" [(ngModel)]="data" (change)="onChange($event)"></ckeditor>

现在,您的数据存储在 retrieveddata 变量中。控制台看看。

StackBlitz Here.

DEMO(检查浏览器的控制台)