本文介紹如何在 Angular 中使用 ng2-ckeditor 控件笔刹,示例代碼基于 angular 6.0.2盖彭,node 8.11.2, ng2-ckeditor 4.9.2 環(huán)境
- 安裝組件
npm install ng2-ckeditor
- 創(chuàng)建 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 />";
}
}
- 創(chuàng)建 ckeditor.component.html
<div>
<ckeditor [(ngModel)]="mycontent" #myckeditor [config]="ckeConfig" debounce="500" (change)="onChange($event)">
</ckeditor>
</div>
<div [innerHTML]="mycontent"></div>
- 修改 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 { }
- 在 index.html 文件頭部標(biāo)簽 <head> 中加入 <script src="https://cdn.ckeditor.com/4.9.2/full-all/ckeditor.js"></script>涮帘, 其中 URL中 4.9.2 是你安裝的 ckeditor 版本號(hào)单寂,根據(jù)自己的實(shí)際情況修改
image
- 在頁面中使用 MyCKEditor 組件贬芥,<my-ckeditor></my-ckeditor>
image
- 最終效果
image
- 總結(jié):也可以不用自己定義一個(gè) MyCKEditor 組件,將 MyCKEditor 組件(ckeditor.component.ts宣决, ckeditor.component.html)的代碼直接應(yīng)用到你要使用的相應(yīng)組件中即可