Angular2 富文本编辑器 ng2-ckeditor 的使用

本文介绍如何在 Angular 中使用 ng2-ckeditor 控件,示例代码基于 angular 6.0.2,node 8.11.2,  ng2-ckeditor 4.9.2 环境
 
1. 安装组件
 
npm install ng2-ckeditor
 

 2. 创建 ckeditor.component.ts 
import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'my-ckeditor',
  templateUrl: './ckeditor.component.html'
})
export class MyCKEditorComponent implements OnInit {
  name = 'ng2-ckeditor';
  ckeConfig: any;
  mycontent: string;
  log: string = '';
  @ViewChild("myckeditor") ckeditor: any;

  constructor() {
    this.mycontent = `<p>My html content</p>`;
  }

  ngOnInit() {
    this.ckeConfig = {
      allowedContent: true,
      extraPlugins: 'divarea'
    };
  }

  onChange($event: any): void {
    console.log("onChange");
    //this.log += new Date() + "<br />";

  }
}
View Code

 

3. 创建 ckeditor.component.html 
 
<div>
    <ckeditor [(ngModel)]="mycontent" #myckeditor [config]="ckeConfig" debounce="500" (change)="onChange($event)">
    </ckeditor>
</div>
<div [innerHTML]="mycontent"></div>

 

4. 修改 app.module.ts,引入 CKEditorModule, CKEditorComponent,及自己定义的组件 MyCKEditorComponent
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { CKEditorModule, CKEditorComponent } from 'ng2-ckeditor';
import { MyCKEditorComponent } from './ckeditor.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, CKEditorModule ],
  declarations: [ AppComponent, MyCKEditorComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

 

 

5. 在 index.html 文件头部标签 <head> 中加入 <script src="https://cdn.ckeditor.com/4.9.2/full-all/ckeditor.js"></script>, 其中 URL中 4.9.2 是你安装的 ckeditor 版本号,根据自己的实际情况修改

 

 
6. 在页面中使用 MyCKEditor 组件,<my-ckeditor></my-ckeditor>
 

 

7. 最终效果

 

8. 总结:也可以不用自己定义一个 MyCKEditor 组件,将 MyCKEditor 组件(ckeditor.component.ts, ckeditor.component.html)的代码直接应用到你要使用的相应组件中即可
 
9. 文中代码结构
 

 

posted @ 2018-05-25 14:03  闪闪发光的馒头  阅读(2922)  评论(0编辑  收藏  举报