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

Angular项目中如何为TinyMCE编辑器添加自定义插件并唤起Angular组件

实现方案

完全可以在Angular环境下给TinyMCE添加自定义插件,核心逻辑是将TinyMCE原生的插件注册能力和Angular的动态组件渲染能力打通,不需要专门找Angular适配的插件示例,按以下步骤操作即可实现你的需求:

第一步:准备自定义Angular组件

先开发好你需要弹出的自定义Angular组件,比如命名为CustomEditorModalComponent,如果是Angular 12及更早版本,需要把该组件加入对应NgModule的entryComponents数组中,Angular 13+版本不需要额外配置,正常在NgModule声明即可。

第二步:注册TinyMCE自定义工具栏按钮

直接在TinyMCE的初始化配置的setup回调中完成自定义按钮注册,这个是TinyMCE原生能力,和Angular框架无冲突,示例代码如下:

// app.component.ts 代码示例
import { Component, ViewContainerRef, ComponentFactoryResolver, Injector } from '@angular/core';
import { CustomEditorModalComponent } from './custom-editor-modal/custom-editor-modal.component';
import { NzModalService } from 'ng-zorro-antd/modal'; // 如果用NG-ZORRO的模态框,也可以用你项目自带的模态框组件

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  constructor(
    private viewContainerRef: ViewContainerRef,
    private modalService: NzModalService,
    private injector: Injector
  ) {}

  tinymceConfig = {
    height: 500,
    menubar: false,
    plugins: 'advlist autolink lists link image charmap',
    toolbar: 'undo redo | formatselect | bold italic | customBtn', // 此处添加自定义按钮的标识
    setup: (editor) => {
      // 注册自定义按钮
      editor.ui.registry.addButton('customBtn', {
        text: '自定义功能',
        icon: 'insert', // 可使用TinyMCE自带图标,也可自定义
        onAction: () => {
          this.openCustomAngularComponent(editor);
        }
      });
    }
  };

  private openCustomAngularComponent(editor: any) {
    // 方式1:用项目自带的模态框加载自定义组件,此处以NG-ZORRO模态框为例
    const modal = this.modalService.create({
      nzTitle: '自定义功能',
      nzContent: CustomEditorModalComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzComponentParams: {
        editorInstance: editor // 把编辑器实例传给自定义组件,方便后续往编辑器插入内容
      },
      nzOnOk: (componentInstance) => {
        // 点击确认的逻辑,比如把自定义组件生成的内容插入编辑器
        editor.insertContent(componentInstance.generatedContent);
      }
    });

    // 方式2:不用第三方UI库模态框,直接动态渲染组件
    // const componentRef = this.viewContainerRef.createComponent(CustomEditorModalComponent);
    // componentRef.instance.editorInstance = editor;
    // // 监听组件的关闭事件,销毁组件
    // componentRef.instance.closeEvent.subscribe(() => {
    //   componentRef.destroy();
    // });
  }
}

第三步:组件和编辑器交互

你在自定义组件中拿到传入的editorInstance实例后,所有操作都可以走TinyMCE原生API,比如插入内容用editorInstance.insertContent(xxx)、获取编辑器内容用editorInstance.getContent(),不存在Angular兼容问题。

注意事项
  • 如果是Angular 14+版本,可以直接用ViewContainerRef.createComponent方法,不需要依赖ComponentFactoryResolver,写法更简洁
  • 如果自定义插件需要多页面复用,可以把注册逻辑封装成Angular服务,不需要每个用到TinyMCE的页面都重复写setup回调
  • 弹窗逻辑不需要绑定TinyMCE自带的弹窗,完全可以复用你项目现有UI库的模态框组件,适配成本更低

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:57:00