Angular CKEditor 5点击工具栏按钮为选中元素添加自定义class的问题
问题原因
CKEditor 5 采用*模型(Model)- 视图(View)*分离的架构,你直接给模型设置class属性不生效有两个核心原因:
- 默认表格的模型Schema没有开放
class属性的允许配置,非法属性会被自动过滤 - 没有配置模型属性到视图DOM的转换规则,就算模型存储了属性,也不会渲染到真实DOM上
具体实现方案
1. 扩展表格模型的Schema,添加自定义属性
不要直接用class作为模型属性名,建议自定义语义化属性名(比如tableStyle)避免冲突,在插件初始化阶段添加Schema配置:
editor.model.schema.extend('table', { allowAttributes: 'tableStyle' });
2. 配置下行转换规则(模型转视图)
把模型里的tableStyle属性转换为DOM上的class或者dataset属性,按需选择对应配置:
场景A:转换为自定义class
editor.conversion.for('downcast').attributeToAttribute({ model: 'tableStyle', view: modelAttributeValue => { return { key: 'class', value: modelAttributeValue } } });
场景B:转换为dataset属性
editor.conversion.for('downcast').attributeToAttribute({ model: 'tableStyle', view: modelAttributeValue => { return { key: 'data-table-type', value: modelAttributeValue } } });
3. (可选)配置上行转换规则(视图转模型)
如果需要编辑器加载已有HTML内容时,能把DOM上的class/data属性自动识别为模型的tableStyle属性,添加上行转换规则:
对应class的上行配置
editor.conversion.for('upcast').attributeToAttribute({ view: { name: 'table', key: 'class' }, model: 'tableStyle' });
对应dataset的上行配置
editor.conversion.for('upcast').attributeToAttribute({ view: { name: 'table', key: 'data-table-type' }, model: 'tableStyle' });
4. 修改原事件逻辑
把原来设置class的代码改为设置自定义的tableStyle属性即可,添加空判断避免异常:
dropdownView.on("execute", function (eventInfo) { const type = eventInfo.source.id; model.enqueueChange("default", (writer) => { const selection = model.document.selection; const table = selection.getFirstPosition().findAncestor("table"); if (!table) return; writer.setAttribute("tableStyle", type, table); }); });
内容的提问来源于stack exchange,提问作者Oki
相关产品推荐
相关产品推荐

