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 = `<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)的代码直接应用到你要使用的相应组件中即可
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 由于项目需要在页面中嵌入一个文本编辑器,因为之前的项目里用的是Ckeditor,所以我现在的项目里也就使用了...
    HalShaw阅读 7,359评论 2 4
  • angular 项目中需要一个富文本编辑器,研究了好几个之后,找到了 ng2-ckeditor 这款编辑器。界面简...
    兜兜转转的小菊阅读 11,459评论 4 5
  • 2018-3-15 星期四 一、安装 注意:请现在终端/控制台窗口中运行 node -v 和 npm -v,来验证...
    ftmo阅读 4,816评论 1 2
  • 空气中若有若无的臭气令人生厌,但却不得不忍受,感觉窒息。喉咙渐渐涌上痒意,想咳嗽,但喉咙却不听指挥。感觉胸中有无数...
    看山缺水阅读 1,220评论 0 0
  • 1.游戏化的本质是使平淡的事情变得好玩。不是生搬硬套游戏手段到学习中。 2.大目标分解成一系列小任务。做到这一点,...
    琢磨概念者阅读 1,504评论 2 0

友情链接更多精彩内容