关于前端:Angular中使用CKEditor5Classic富文本编辑器

49次阅读

共计 3211 个字符,预计需要花费 9 分钟才能阅读完成。

前言

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

步骤

1. 首先从官网构建包。

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

3.index 文件中引入 js

 <script type="text/javascript" src="assets/ckeditor5/build/ckeditor.js" charset="UTF-8"></script>

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 中退出代码

<textarea class="form-control" name="content" id="editor" style="resize: none;" placeholder="请输出内容"></textarea>

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

正文完
 0