gypjoy

全干工程师

angular2中使用ckeditor5教程

在大多数场景中我们需要一个富文本编辑器. 下面我们将讲解ckeditor5集成到angular2中的方法和一些使用的基础.
在此之前你需要一些angular2的使用经验,你可以通过这篇文章学习来学习angluar2.

angular2-ckeditor5

安装

创建工程,增加工程依赖.


[meshell@root] ng new angular2-ckeditor5

# ckeditor5核心
[meshell@root] npm install --save @ckeditor/ckeditor5-angular 

# ckeditor5功能主题,官方提供5种类型,当然你也可以自定义build
[meshell@root] npm install --save @ckeditor/ckeditor5-build-decoupled-document

在上述命令中我们创建了一个angular2-cheditor5的angular2工程. 紧接着安装了两个ckeditor5的包.

集成

我们只需要导入相关的包就可以轻松集成ckeditor5,需要导入CKEditorModuleapp.module.ts中,再将@ckeditor/ckeditor5-build-decoupled-document引入到app.component.ts中就像这样.

// app.module.ts
@NgModule({
  ...
  imports: [
    BrowserModule,
    AppRoutingModule,
    CKEditorModule // 必须引入
  ],
  ...
})
// app.component.ts
...
import * as DocumentEditor from '@ckeditor/ckeditor5-build-decoupled-document';
...

完成上面的代码,我们就可以使用ckeditor5了。

使用

使用也非常简单,只需要在模板文件中使用<ckeditor>标签就行, 绑定[editor], [config]属性.

<!-- app.component.html -->
...

<ckeditor [editor]="Editor" [config]="config" (ready)="onReady($event)"></ckeditor>

Note: 需要注意的是我们用得是docuemnt功能主题类型是需要自己调用(ready)事件来完成渲染的.

// app.component.ts
export class AppComponent {

  ...

  public Editor = DocumentEditor;

  config = {
    placeholder: '默认显示语',
    // language: 'zh-cn', // 语言配置
    // toolbar: [], // 功能配置
    // plugins: [], // 插件配置
  };


  onReady(editor) {
    editor.ui.getEditableElement().parentElement.insertBefore(
      editor.ui.view.toolbar.element,
      editor.ui.getEditableElement()
    );
  }

}

Note: 如果你需要设置语言,需要先加载语言文件.

# app.component.ts
import '@ckeditorckeditor5-build-decoupled-document/build/translations/zh-cn';

获取内容

通过(change) 事件我们可以直接获得编辑器内容.

<!-- app.component.html -->
 <ckeditor [editor]="Editor" (change)="onChange($event)" [config]="config" (ready)="onReady($event)"></ckeditor>
// app.component.ts
...
export class AppComponent {
  ...
  content = '';
  onChange({editor}: ChangeEvent) {
    const data = editor.getData();
    console.log(data);
    this.content = data;
  }
}

其实事件获取内容的方法可以用model来做, ckeditor5是支持model绑定的.

model绑定

通过[(ngModel)]我们可以直接内容绑定到变量.

<!-- app.component.html -->
 <ckeditor [editor]="Editor" [(ngModel)]="content"  (change)="onChange($event)" [config]="config" (ready)="onReady($event)"></ckeditor>

整个angular2中使用ckeditor5的内容我们就到此为止,如果大有什么疑问的话可以留言。

推荐阅读

  1. 官方文档
  2. angular文档
  3. 源代码
  4. 在线DEMO

留言