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. 文中代碼結構
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM