angularAngular2.0

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

2018-10-12  本文已影响183人  杀个程序猿祭天

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

  1. 安装组件
npm install ng2-ckeditor
  1. 创建 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 />";

  }
}
  1. 创建 ckeditor.component.html
<div>
    <ckeditor [(ngModel)]="mycontent" #myckeditor [config]="ckeConfig" debounce="500" (change)="onChange($event)">
    </ckeditor>
</div>
<div [innerHTML]="mycontent"></div>
  1. 修改 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 { }
  1. 在 index.html 文件头部标签 <head> 中加入 <script src="https://cdn.ckeditor.com/4.9.2/full-all/ckeditor.js"></script>, 其中 URL中 4.9.2 是你安装的 ckeditor 版本号,根据自己的实际情况修改
image
  1. 在页面中使用 MyCKEditor 组件,<my-ckeditor></my-ckeditor>
image
  1. 最终效果
image
  1. 总结:也可以不用自己定义一个 MyCKEditor 组件,将 MyCKEditor 组件(ckeditor.component.ts, ckeditor.component.html)的代码直接应用到你要使用的相应组件中即可
上一篇 下一篇

猜你喜欢

热点阅读