我正在尝试从 CKEditor 获取数据?我正在尝试 getData 函数,但它似乎不起作用。
下面是 HTML
<ckeditor [editor]="Editor" id="Editor" [data]="editorData"></ckeditor>
下面是 typescript
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 不是函数。
最佳答案
这是完整的路径:
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());
}
<强> DEMO (检查浏览器的控制台)
对于 CKEditor 经典版:
如果您想获取数据,有两种选择:
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
变量中。安慰它看看。
DEMO (检查您的浏览器控制台)
关于angular - 如何从CKEditor获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58155972/