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

本文介绍如何在 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 = `

My html content

`; } ngOnInit() { this.ckeConfig = { allowedContent: true, extraPlugins: 'divarea' }; } onChange($event: any): void { console.log("onChange"); //this.log += new Date() + "
"; } }
  1. 创建 ckeditor.component.html
  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 文件头部标签 中加入 , 其中 URL中 4.9.2 是你安装的 ckeditor 版本号,根据自己的实际情况修改
image
  1. 在页面中使用 MyCKEditor 组件,
image
  1. 最终效果
image
  1. 总结:也可以不用自己定义一个 MyCKEditor 组件,将 MyCKEditor 组件(ckeditor.component.ts, ckeditor.component.html)的代码直接应用到你要使用的相应组件中即可

你可能感兴趣的:(Angular2 富文本编辑器 ng2-ckeditor 的使用)