如何在角度2

时间:2017-01-23 21:46:38

标签: angular

我正在尝试将CKEditor集成到我的角度项目中。我已经遵循了其他类似的解决方案,但只出现了textarea。这是我到目前为止所做的。

HTML

<!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>

JS

import {Component} from '@angular/core';

@Component({
    selector: 'test',
    templateUrl:'test.html'
})

export class TestComponent {

}

4 个答案:

答案 0 :(得分:22)

从Angular 4开始angular-cli是构建和管理Angular项目的标准工具。

这些是在Angular 4应用程序中启动和测试CKEditor的步骤。

假设已安装angular-cli

1。创建一个新的Angular应用程序

$ ng new ckeditorSample --skip-test
$ cd ckeditorSample

2。安装ng2-ckeditor

ng2-ckeditor是Angular 2及更高版本的CKEditor集成包。

$ npm install --save ng2-ckeditor
$ npm update

3。添加SampleEditor组件

修改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';
}

4。添加SampleEditor查看器模板

修改src/app/app.component.html以调用SampleEditor组件。

<div>
  <sampleEditor></sampleEditor>
</div>

5。将CKEditor模块添加到Angular应用程序

修改src/app/app.module.ts以包含CKEditorModuleSampleEditor组件。

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 { }

6。将最新的CKEditor脚本从CDN添加到Angular框架

修改src/index.html以包含最新的脚本。

截至撰写本文时: 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>

7。运行应用程序

npm start &
firefox http://localhost:4200

http://localhost:4200上打开浏览器 CKEditor应该在那里。

答案 1 :(得分:6)

您可以使用包装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);
        }
    }

答案 2 :(得分:2)

我不允许在我的项目中使用cdn,我还需要在我的项目中添加插件。能够使用npm做到这一点。这是我解决这个问题的方法

使用npm。使用ckeditor安装ng2-ckeditor。

npm install --save ckeditor

npm install --save ng2-ckeditor

更新 angular-cli.json ,以便能够将插件添加到CKEditor的实例中。在 angular-cli.json的资产部分中添加:

"assets": [
    "assets",
    "favicon.ico",
    {
       "glob": "**/*", 
       "input": "../node_modules/ckeditor/", 
       "output": "assets/js/ckeditor/", 
       "allowOutsideOutDir": true
    }
 ]

ckeditor.js 从下载的npm添加到 angular-cli.json 中的script-tag:

"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文件有注释。

答案 3 :(得分:0)

如果要将CKEditor 5编辑器与Angular 2+框架集成在一起,可以使用ready-to-use official integration,它提供了简单而有意识的API:

editor.component.html

<ckeditor
    [editor]="Editor"
    [data]="editorData"
    [config]="config"
    [disabled]="isDisabled"

    (ready)="onReady($event)"
    (change)="onChange($event)"
    (focus)="onFocus($event)"
    (blur)="onBlur($event)">
</ckeditor>

editor.component.ts

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 {}
}

app.module.ts

import { CKEditorModule } from '@ckeditor/ckeditor5-angular';

@NgModule({
  declarations: [
      // ...
  ],
  imports: [
      CKEditorModule,
      // ...
  ],
  // ...
})
export class AppModule { }