Angular中使用CKEditor5(Classic富文本编辑器)

前言

这里我使用的是在线构建。网址附上:https://ckeditor.com/ckeditor-5/

步骤

1.首先从官网构建包。

2.将下载的包放在项目中assets下面

3.index文件中引入js

 

4.在你需要用到富文本的页面引入

declare var ClassicEditor: any;

5.页面初始化加载富文本

public Editor;

  ngOnInit() {
        this._init_Editor();
  }
// 初始化富文本
    _init_Editor() {
        ClassicEditor.create(document.querySelector('#editor'), {
            toolbar: {
                items: [
                    'heading', '|', 'Alignment', 'FontSize', 'FontColor', 'FontFamily', 'Highlight',
                    'bold', 'italic',
                    'link', '|',
                    'bulletedList', 'numberedList',
                    'insertTable', '|',
                    'uploadImage', 'ImageResize', '|',
                    'undo', 'redo'
                ],
                viewportTopOffset: 30,
                shouldNotGroupWhenFull: true
            },
            image: {
                toolbar: [
                    'imageStyle:alignLeft', 'imageStyle:alignCenter', 'imageStyle:alignRight',
                    '|',
                    'resizeImage',
                    '|',
                    'imageTextAlternative'
                ],
                styles: [
                    'alignLeft', 'alignCenter', 'alignRight'
                ],
                resizeOptions: [{
                        name: 'resizeImage:original',
                        label: 'Original',
                        value: null
                    },
                    {
                        name: 'resizeImage:25',
                        label: '25%',
                        value: '25'
                    },
                    {
                        name: 'resizeImage:50',
                        label: '50%',
                        value: '50'
                    },
                    {
                        name: 'resizeImage:75',
                        label: '75%',
                        value: '75'
                    }
                ],
            },
            language: 'zh-cn'
        }).then((editor) => {
            this.Editor = editor;
        }).catch((err) => {
            console.log(err)
        });
    }

6.html中加入代码

7.强制修改富文本最小高度

.ck-editor__editable { 
    min-height: 300px;
    margin-bottom: 20px; 
}

到这里富文本都能出来啦!但是这里是不包含上传的。


上传图片

ckfinder: {
    uploadUrl: 'xxxxxx'
}

在_init_Editor()方法中加入上传地址。就可以了。


但是后台可能会防止恶意上传,接口需要带token。这里我没找到关于header的属性。所以可以写一个上传适配器。这里的ckfinder就不用写了。需要在assets下新建一个js文件

创建MyUploadAdapter.js文件

export class UploadAdapter {
    constructor( loader ) {
       this.loader = loader;
    }

    // Starts the upload process.
    upload() {
        return this.loader.file
            .then( file => new Promise( ( resolve, reject ) => {
                this._initRequest();
                this._initListeners( resolve, reject, file );
                this._sendRequest( file );
            } ) );
    }

    // Aborts the upload process.
    abort() {
        if ( this.xhr ) {
            this.xhr.abort();
        }
    }
    _initRequest() {
        const xhr = this.xhr = new XMLHttpRequest();
        
        xhr.open( 'POST', 'xxxxxxxxx', true );
        xhr.setRequestHeader( 'token', sessionStorage.getItem('token'));
        xhr.responseType = 'json';//返回值json格式
    }


    _initListeners( resolve, reject, file ) {
        const xhr = this.xhr;
        const loader = this.loader;
        const genericErrorText = `Couldn't upload file: ${ file.name }.`;

        xhr.addEventListener( 'error', () => reject( genericErrorText ) );
        xhr.addEventListener( 'abort', () => reject() );
        xhr.addEventListener( 'load', () => {
            const response = xhr.response;
            if ( !response || response.error ) {
                return reject( response && response.error ? response.error.message : genericErrorText );
            }
            resolve( {
                default: response.url
            } );
        } );


        if ( xhr.upload ) {
            xhr.upload.addEventListener( 'progress', evt => {
                if ( evt.lengthComputable ) {
                    loader.uploadTotal = evt.total;
                    loader.uploaded = evt.loaded;
                }
            } );
        }
    }


    _sendRequest( file ) {
        const data = new FormData();
        data.append( 'upload', file );
        this.xhr.send( data );
    }
}
export function MyCustomUploadAdapterPlugin( editor ) {
    editor.plugins.get( 'FileRepository' ).createUploadAdapter = ( loader ) => {
        return new UploadAdapter( loader );
    };
}

在富文本编辑器引入

import {
    UploadAdapter
} from 'assets/js/MyUploadAdapter';

在_init_Editor()方法中then里加入

editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
   return new UploadAdapter(loader);
};

结束

其他

1.获取内容
this.Editor.getData()
2.设置内容
this.Editor.setData(${this.content})
3.只读
this.Editor.isReadOnly = true;
4.后台接口返回格式为

{
    "uploaded": true,
    "url": "http://xxxxx/uploaded-image.jpeg"
}

你可能感兴趣的:(Angular中使用CKEditor5(Classic富文本编辑器))