[英]How to integrate CKEditor in angular 2
我正在嘗試將CKEditor集成到我的角度項目中。 我已經遵循了其他類似的解決方案,但只出現了textarea。 這是我到目前為止所做的。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="../Email/ckeditor/ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
import {Component} from '@angular/core';
@Component({
selector: 'test',
templateUrl:'test.html'
})
export class TestComponent {
}
從Angular 4開始, angular-cli是構建和管理Angular項目的標准工具。
這些是在Angular 4應用程序中啟動和測試CKEditor的步驟。
假設安裝了angular-cli
。
$ ng new ckeditorSample --skip-test
$ cd ckeditorSample
ng2-ckeditor是Angular 2及更高版本的CKEditor集成包。
$ npm install --save ng2-ckeditor
$ npm update
修改src/app/app.component.ts
以包括SampleEditor
組件。
import { Component } from '@angular/core';
@Component({
selector: 'sampleEditor',
template: `
<ckeditor
[(ngModel)]="ckeditorContent"
[config]="{uiColor: '#a4a4a4'}"
(change)="onChange($event)"
(ready)="onReady($event)"
(focus)="onFocus($event)"
(blur)="onBlur($event)"
debounce="500">
</ckeditor>
`,
})
export class SampleEditor {
private ckeditorContent: string;
constructor() {
this.ckeditorContent = `<p>Greetings from CKEditor...</p>`;
}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
}
修改src/app/app.component.html
調用SampleEditor
組件。
<div>
<sampleEditor></sampleEditor>
</div>
修改src/app/app.module.ts
以包括CKEditorModule
和SampleEditor
組件。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CKEditorModule } from 'ng2-ckeditor';
import { AppComponent, SampleEditor } from './app.component';
@NgModule({
declarations: [
AppComponent,
SampleEditor
],
imports: [
BrowserModule,
FormsModule,
CKEditorModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
修改src/index.html
以包含最新的腳本。
截至撰寫本文時: https://cdn.ckeditor.com/4.7.0/standard-all/ckeditor.js
: https://cdn.ckeditor.com/4.7.0/standard-all/ckeditor.js
查看最新信息: http : //cdn.ckeditor.com/
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CkeditorSample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://cdn.ckeditor.com/4.7.0/standard-all/ckeditor.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
npm start &
firefox http://localhost:4200
在http:// localhost:4200上打開瀏覽器CKEditor應該在那里。
您可以使用包裝CKEditor庫的組件:
https://github.com/chymz/ng2-ckeditor
這使得它非常容易並提供雙向綁定:
<ckeditor [(ngModel)]="content" [config]="config"></ckeditor>
編輯:
另一種選擇是使用我從ng2-ckeditor
重構並簡化的這個模塊。 這樣您就不必安裝和管理其他依賴項。
1.創建文件ckeditor.module.ts
2.粘貼內容
import { Component, Input, OnInit, OnDestroy, ViewChild, ElementRef, forwardRef, NgZone, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
declare const CKEDITOR;
@Component({
selector: 'app-ckeditor',
template: `
<textarea #editor>
{{value}}
</textarea>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CkEditorComponent),
multi: true
}]
})
export class CkEditorComponent implements OnInit, OnDestroy, ControlValueAccessor {
@ViewChild('editor') editor: ElementRef;
wait = false;
instance: any;
config = {
uiColor: '#F0F3F4',
height: '100%'
};
private _value = '';
get value(): any { return this._value; }
@Input() set value(v) {
if (v !== this._value) {
this._value = v;
this.onChange(v);
}
}
constructor(private zone: NgZone) { }
ngOnInit() {
this.instance = CKEDITOR.replace(this.editor.nativeElement, this.config);
this.instance.setData(this._value);
// CKEditor change event
this.instance.on('change', () => {
let value = this.instance.getData();
this.updateValue(value);
});
}
/**
* Value update process
*/
updateValue(value: any) {
this.zone.run(() => {
this.value = value;
this.onChange(value);
this.onTouched();
});
}
/**
* Implements ControlValueAccessor
*/
writeValue(value: any) {
console.log('writeValue');
this._value = value;
if (this.instance) {
this.instance.setData(value);
}
}
onChange(_: any) { }
onTouched() { }
registerOnChange(fn: any) { this.onChange = fn; }
registerOnTouched(fn: any) { this.onTouched = fn; }
ngOnDestroy() {
if (this.instance) {
setTimeout(() => {
this.instance.removeAllListeners();
CKEDITOR.instances[this.instance.name].destroy();
this.instance.destroy();
this.instance = null;
});
}
}
}
@NgModule({
imports: [],
declarations: [CkEditorComponent],
providers: [],
exports: [CkEditorComponent]
})
export class CkEditorModule { }
3.像這樣使用
import { CkEditorModule } from '../../';
<app-ckeditor formControlName="postContent"></app-ckeditor>
4.我需要使用此功能時動態加載腳本
public addCkEditor(permissions) {
if (this.usesCKEditor(permissions) && !window['CKEDITOR']) {
const url = '//cdn.ckeditor.com/4.7.3/full/ckeditor.js';
const script = document.createElement('script');
script.onload = () => {
this.ckeditorLoaded.next(true);
};
script.type = 'text/javascript';
script.src = url;
document.body.appendChild(script);
}
}
我不允許在我的項目中使用cdn,我還需要為我的項目添加插件。 能夠使用npm做到這一點。 這是我解決這個問題的方法
使用npm使用ckeditor安裝ng2-ckeditor。
npm install --save ckeditor
和
npm install --save ng2-ckeditor
更新angular-cli.json以便能夠將插件添加到CKEditor的實例中。 在angular-cli.json的assets部分中添加:
"assets": [
"assets",
"favicon.ico",
{
"glob": "**/*",
"input": "../node_modules/ckeditor/",
"output": "assets/js/ckeditor/",
"allowOutsideOutDir": true
}
]
還添加從下載的NPM在角cli.json腳本標簽ckeditor.js:
"scripts": [
"../node_modules/ckeditor/ckeditor.js"
]
將需要使用的插件下載到項目的/ assets / js / ckeditor / plugins /文件夾中。 確保插件文件夾的每個子文件夾中都存在plugin.js文件。
使用以下內容為ckeditor創建自己的配置文件assets / js / ckeditor / ckeditor-config.js:
(function(){
CKEDITOR.basePath = '/assets/js/ckeditor/'
CKEDITOR.plugins.addExternal('wordcount', 'plugins/wordcount/');
CKEDITOR.plugins.addExternal('notification', 'plugins/notification/');
CKEDITOR.editorConfig = function( config ) {
config.extraPlugins = 'wordcount,notification';
}
})();
創建一個內部服務,以便能夠使用您自己的輸入配置您的ckeditor。 在這里,我使用該服務調整高度,並從我的ckeditor組件設置我的字符的最大限制。 我也告訴插件只顯示字符計數器。
import { Injectable } from '@angular/core';
@Injectable()
export class CkeditorConfigService {
constructor() { }
public getConfig(height: number, maxCharCount: number){
return {
customConfig: '/assets/js/ckeditor/ckeditor-config.js',
height: height,
wordcount: {
showParagraphs: false,
showWordCount: false,
showCharCount: true,
maxCharCount: maxCharCount
}
};
}
}
由於ckeditor是表單部分,您需要將FormsModule添加到app.module.ts以及ng2-ckeditor模塊。
imports: [
...
FormsModule,
CKEditorModule,
...
]
從您的組件添加內部服務。
@Component({
selector: 'test-ckeditor-app',
templateUrl: './editor.component.html',
providers: [
CkeditorConfigService
]
})
export class EditorComponent implements OnInit {
ckeditorContent: string = '<p>Some html</p>';
private myCkeditorConfig: any;
constructor(private ckService: CkeditorConfigService) {}
ngOnInit() {
this.myCkeditorConfig = this.ckService.getConfig(150, 400);
}
}
最后在你的html文件中添加以下內容:
<ckeditor
[(ngModel)]="ckeditorContent"
[config]="myCkeditorConfig">
</ckeditor>
請在github上找到我的項目示例:
https://github.com/dirbacke/ckeditor4
注意! 編譯和運行時,您將收到MIME類型控制台警告。 那是因為警告中指定的css文件有注釋。
如果您想將CKEditor 5編輯器與Angular 2+框架集成 ,那么可以使用即用型官方集成 ,它提供簡單而有意識的API:
<ckeditor
[editor]="Editor"
[data]="editorData"
[config]="config"
[disabled]="isDisabled"
(ready)="onReady($event)"
(change)="onChange($event)"
(focus)="onFocus($event)"
(blur)="onBlur($event)">
</ckeditor>
import '@ckeditor/ckeditor5-build-classic/build/translations/de';
import * as ClassicEditorBuild from '@ckeditor/ckeditor5-build-classic';
@Component( {
selector: 'editor',
templateUrl: './editor.component.html',
styleUrls: [ './editor.component.css' ]
} )
export class SimpleUsageComponent {
public Editor = ClassicEditorBuild;
public editorData = '<p>Ckeditor5 & Angular</p>';
public config = {
language: 'de'
};
public isDisabled = false;
onReady( editor ): void {}
onChange( event ): void {}
onFocus( event ): void {}
onBlur( event ): void {}
}
import { CKEditorModule } from '@ckeditor/ckeditor5-angular';
@NgModule({
declarations: [
// ...
],
imports: [
CKEditorModule,
// ...
],
// ...
})
export class AppModule { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.