如何在Angular 12的CKEditor 5第4版本中添加自定义按钮
在CKEditor 5 v4工具栏添加特殊按钮的实操步骤
一、确认按钮对应插件状态
如果是CKEditor官方提供的特殊按钮(比如特殊字符按钮),先检查项目是否安装了对应插件包:
- npm安装:
npm install @ckeditor/ckeditor5-special-characters --save - yarn安装:
yarn add @ckeditor/ckeditor5-special-characters
如果是自定义按钮,先确保插件代码已正确实现(比如定义命令和按钮视图)。
二、在编辑器配置中注册插件
初始化编辑器时,将插件加入plugins数组,同时把按钮名添加到toolbar配置项:
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor'; import SpecialCharacters from '@ckeditor/ckeditor5-special-characters/src/specialcharacters'; import SpecialCharactersEssentials from '@ckeditor/ckeditor5-special-characters/src/specialcharactersessentials'; ClassicEditor .create( document.querySelector( '#editor' ), { plugins: [ SpecialCharacters, SpecialCharactersEssentials, /* 其他已启用插件 */ ], toolbar: [ /* 原有工具栏项 */, 'specialCharacters' ] } ) .then( editor => { console.log( 'Editor initialized', editor ); } ) .catch( error => { console.error( error.stack ); } );
三、自定义特殊按钮实现示例
如果是自己开发的按钮(比如插入固定特殊内容),参考以下插件写法:
// 自定义插件代码 import Plugin from '@ckeditor/ckeditor5-core/src/plugin'; import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview'; export default class CustomSpecialButton extends Plugin { init() { const editor = this.editor; // 注册插入命令 editor.commands.add( 'insertCustomContent', { execute() { editor.model.change( writer => { editor.model.insertContent( writer.createText( '自定义特殊内容' ) ); } ); } } ); // 注册按钮到工具栏 editor.ui.componentFactory.add( 'customSpecialButton', locale => { const view = new ButtonView( locale ); view.set( { label: '插入特殊内容', tooltip: true // 可选:添加图标,比如 icon: '<svg>...</svg>' } ); // 绑定按钮状态与命令 view.bind( 'isOn', 'isEnabled' ).to( editor.commands.get( 'insertCustomContent' ), 'value', 'isEnabled' ); this.listenTo( view, 'execute', () => { editor.execute( 'insertCustomContent' ); editor.editing.view.focus(); } ); return view; } ); } }
之后在编辑器配置中引入该插件,把'customSpecialButton'加入toolbar数组即可。
常见问题排查
- 按钮不显示:检查插件是否正确注册、工具栏数组中的按钮名称是否与插件注册的一致
- 按钮点击无反应:确认命令逻辑正确,编辑器处于可编辑状态
- 依赖报错:确保所有插件包版本与CKEditor 5 v4版本匹配
内容的提问来源于stack exchange,提问作者murato
相关产品推荐
相关产品推荐

