You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何为CKEditor添加插入自定义表格的自定义插件?求示例

Angular项目集成CKEditor自定义插入表格插件实现方案

之前两种引入方式失效的核心原因:

  • index.html通过script标签引入本地bundle的方式,会因为Angular构建时的资源路径哈希、全局作用域隔离、脚本加载时序问题,导致CKEDITOR全局对象无法被Angular组件正确读取
  • 组件内直接import本地bundle的方式,既不符合CKEditor5的ES模块加载规范,也没有走Angular CKEditor组件的插件注册逻辑,自然无法加载自定义插件

第一步:安装依赖

不要使用零散打包的自定义bundle,直接安装官方适配包和核心依赖:

npm install @ckeditor/ckeditor5-angular @ckeditor/ckeditor5-build-classic
npm install @ckeditor/ckeditor5-table

第二步:编写自定义表格插入插件

在项目src目录下新建ckeditor-plugins/custom-table-insert目录,创建custom-table-insert.js插件文件,基础实现示例如下:

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
import Table from '@ckeditor/ckeditor5-table/src/table';

export default class CustomTableInsert extends Plugin {
  // 声明依赖官方基础表格插件
  static get requires() {
    return [Table];
  }

  init() {
    const editor = this.editor;
    // 注册工具栏按钮
    editor.ui.componentFactory.add('customInsertTable', (locale) => {
      const button = new ButtonView(locale);
      button.set({
        label: '插入自定义表格',
        icon: '<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M3 3h14v14H3V3zm2 2v4h4V5H5zm6 0v4h4V5h-4zm-6 6v4h4v-4H5zm6 0v4h4v-4h-4z"/></svg>',
        tooltip: true
      });

      // 按钮点击后的插入逻辑,可根据需求自定义
      button.on('execute', () => {
        editor.model.change(writer => {
          const insertPosition = editor.model.document.selection.getFirstPosition();
          // 创建带自定义属性的表格节点,示例为3行3列、带自定义类名的表格
          const tableNode = writer.createElement('table', {
            class: 'custom-table',
            'data-table-type': 'business-table'
          });

          // 循环生成表格行和单元格
          for (let row = 0; row < 3; row++) {
            const tr = writer.createElement('tableRow');
            for (let col = 0; col < 3; col++) {
              const td = writer.createElement('tableCell');
              writer.insertText(`单元格${row+1}-${col+1}`, td);
              writer.append(td, tr);
            }
            writer.append(tr, tableNode);
          }

          writer.insert(tableNode, insertPosition);
        });
      });

      return button;
    });
  }
}

如果需要让用户自定义表格行列数、样式属性,可以在按钮点击回调中唤起Angular项目内的弹窗组件,拿到用户输入参数后再执行表格插入逻辑,不需要把弹窗逻辑耦合在插件代码中。

第三步:Angular模块注册CKEditor

在需要使用编辑器的业务模块(如app.module.ts)中导入CKEditor模块:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CKEditorModule } from '@ckeditor/ckeditor5-angular';
import { AppComponent } from './app.component';
import { EditorDemoComponent } from './editor-demo/editor-demo.component';

@NgModule({
  declarations: [
    AppComponent,
    EditorDemoComponent
  ],
  imports: [
    BrowserModule,
    CKEditorModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

第四步:组件中加载编辑器和自定义插件

在业务组件中配置编辑器参数,加载自定义插件:

import { Component } from '@angular/core';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import CustomTableInsert from '../ckeditor-plugins/custom-table-insert/custom-table-insert';
import TableToolbar from '@ckeditor/ckeditor5-table/src/tabletoolbar';

@Component({
  selector: 'app-editor-demo',
  template: `
    <ckeditor
      [editor]="editorInstance"
      [config]="editorConfig"
      (ready)="handleEditorReady($event)"
    ></ckeditor>
  `
})
export class EditorDemoComponent {
  public editorInstance = ClassicEditor;
  public editorConfig = {
    plugins: [
      TableToolbar,
      CustomTableInsert
    ],
    toolbar: {
      items: [
        'heading', '|',
        'bold', 'italic', '|',
        'customInsertTable', '|',
        'undo', 'redo'
      ]
    },
    table: {
      contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells']
    }
  };

  handleEditorReady(editor: any) {
    // 可在此处存储编辑器实例,供后续业务逻辑调用
    console.log('编辑器加载完成', editor);
  }
}

常见问题处理

  • 构建时报错找不到CKEditor内部依赖:在tsconfig.json的compilerOptions中添加"allowJs": true,允许构建时编译JS格式的插件文件即可
  • 自定义表格样式不生效:直接在Angular全局样式文件或组件样式文件中编写对应表格类名的CSS规则即可,示例:
.custom-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e5e7eb;
}
.custom-table td {
  border: 1px solid #e5e7eb;
  padding: 8px 12px;
}
  • 不要通过index.html的script标签引入CKEditor资源,所有依赖统一走npm安装+ES模块import的方式,完全适配Angular的构建规则,不会出现加载时序、作用域隔离类的问题
  • 如果需要做更复杂的表格编辑功能,可以基于CKEditor5的表格API扩展插件逻辑,所有插件注册都通过editorConfig的plugins字段传入即可,不需要修改CKEditor源码

内容的提问来源于stack exchange,提问作者slouma allagui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 08:39:20