Angular8集成Tinymce5

一、Tinymce5简介

描述:TinyMCE是一款易用、且功能强大的所见即所得的富文本编辑器。同类插件有:UEditor、Kindeditor、Simditor、CKEditor、wangEditor、Suneditor、froala等等。

官网:Tinymce 官网

官网及文档(中文):Tinymce 中文文档(不全)

二、Angular8集成Tinymce5

  1. 安装tinymce
    npm install --save-dev tinymce

  2. 安装ngx-tinymce
    npm install --save-dev ngx-tinymce@7.0.0
    注:通过ngx-tinymce中间件更方便的使用tinymce,还有其他中间件,如:@tinymce/tinymce-angular
    在这里插入图片描述

3.导入ngx-tinymce模块
修改文件:app.module.ts

...
import { NgxTinymceModule } from 'ngx-tinymce';
...
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgZorroAntdModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    // 增加tinymce的导入
    NgxTinymceModule.forRoot({
      baseURL: './assets/library/tinymce/'
    })
  ],
  bootstrap: [AppComponent]
})
  1. 把node_modules中的tinymce文件夹中的部分文件(如下图目录)移入assets下的文件,文件路径需要和NgxTinymceModule中的baseURL一致;
    在这里插入图片描述
    注意:一定不能全部复制到assets,否则会报错,tinymce无法正常加载

  2. 在需要使用富文本编辑组件的模块,引入NgxTinymceModule:

...
import { NgxTinymceModule } from 'ngx-tinymce';

@NgModule({
  declarations: [DiaryComponent],
  imports: [
    CommonModule,
    FormsModule,
    DiaryRoutingModule,
    NgxTinymceModule
  ]
})
export class DiaryModule { }
  1. 在html文件中创建tinymce的Dom
<tinymce [(ngModel)]="data" [config]="initConfig"></tinymce>
  1. 在component文件修改:
...
initTinymce(){
    this.initConfig = {
      placeholder: '请输入内容',// 占位符
      // 高度 max_height, max_width, min_height, min_width
      min_height: 600,
      // 换行时,是否保留当前样式
      keep_styles: true,
      // html版本
      // 该值默认是html5,可选值还有:html4、html5-strict。
      // html5模式是完整的HTML5规范,它兼容旧的HTML4。html5-strict是HTML5的严格模式,它只允许HTML5规范的元素,不包括已经被移除标准的元素。html4模式则是包括完整的HTML4过渡规范。在需要兼容老旧浏览器时,可能会用到该选项。
      schema: 'html5',
      // 隐藏状态栏 取消底部标签和组件介绍信息 状态栏是与编辑器的可编辑区域底部对齐的灰色栏。状态栏包含路径信息和调整大小手柄。删除状态栏将使用户无法更改可编辑区域的大小。
      statusbar: true, 
      // 是否允许改变高度,statusbar必须为true, 默认: true(仅允许改变高度), false(完全不让你动), 'both'(宽高都能改变,注意引号)
      resize: true,  
      // 禁用状态栏的元素路径显示
      elementpath: false,  
      // 禁用状态栏信息 使用该branding选项可以禁用状态栏中显示的“由Tiny提供支持”链接,以进行产品归因。重要提示:免费和开放源代码用户必须提供产品归因。有关TinyMCE归属要求的信息,请参阅:徽标和归属要求。
      branding: false,
      // 语言
      language: 'zh_CN',  
      // 浏览器的拼写检查
      // browser_spellcheck: true,     
      // 支持鼠标右键的组件
      contextmenu: 'link image table media',   
      // 禁用鼠标右键时打开浏览器菜单弹框,配合contextmenu使用,否则右键不弹框
      contextmenu_never_use_native: true,
      // 对话框支持拖动
      draggable_modal: true, 
      // 开启拖入功能,true:禁止拖入
      paste_block_drop: false,
      // 允许粘贴图片
      paste_data_images: true,
      // 禁用默认粘贴过滤器
      paste_enable_default_filters: false,
      paste_filter_drop: false,
      // 禁用样式粘贴过滤器
      paste_remove_styles_if_webkit: false,
      // 检测类似于URL的文本,然后将其更改为超链接。
      // 检测类似于图像URL的文本,并尝试用图像替换文本。
      smart_paste: true,
      // 粘贴前的处理
      paste_preprocess: (plugin, args) => {
      },
      // 粘贴到组件后,添加dom属性,组件默认添加了div,通过控制台可以看出该位置的div的id为12了
      paste_postprocess: (plugin, args) => {
      },
      // 允许粘贴的元素,不管用
      // paste_word_valid_elements: 'strong,h1,h2',
      // 图片高级功能
      image_advtab: true,
      // 图片对话框中上传标签开关,false时只可以输入图片路径,没有上传入口
      image_uploadtab: true, 
      // 是否开启图片标题设置的选择,这里设置否
      image_title: false,
      // 启用或禁用自动上传URL或Blob URI表示的图像
      automatic_uploads: true,
      // 自动生成图片名称
      images_reuse_filename: true,
      // 是否开启自动保存,退出页面或刷新时提示
      autosave_ask_before_unload: true,
      // 自动保存时间间隔 秒
      autosave_interval: '30s',  
      // 本地保存数据的有效期 分
      autosave_retention: "5m",   
      // 组件崩溃后是否自动还原最后保存的内容
      autosave_restore_when_empty: true,
      // 禁用快速工具栏
      quickbars_selection_toolbar: false,    
      // 目录级别个数H1通过H9
      toc_depth: 9,
      // 粘性工具栏(或停靠工具栏),当向下滚动网页直到不再可见编辑器时,会将工具栏和菜单停靠在屏幕顶部。
      toolbar_sticky: true,
      // 工具栏位置 auto,top,bottom
      toolbar_location: 'top',
      // 工具栏的样式 'floating','sliding','scrolling',或者'wrap'
      toolbar_mode: 'floating',
      // 类名称
      template_cdate_classes: "cdate creationdate", 
      // 模板日期格式设置
      template_cdate_format: "%m/%d/%Y - %H:%M:%S",
      // 组件,在这里配置的组件才会生效
      plugins: [
      'toc advlist',
      'autolink lists link image charmap print preview anchor template',
      'searchreplace visualblocks code fullscreen pagebreak media',
      'insertdatetime table paste code help wordcount imagetools directionality autosave emoticons hr searchreplace codesample visualchars'
      ],   
      // 工具栏分类 
      menubar: 'file edit insert view format table help export',  
      menu: {
      file: { title: 'File', items: 'newdocument undo redo | preview | print ' },
      edit: { title: 'Edit', items: 'undo redo | cut copy paste | selectall | searchreplace' },
      view: { title: 'View', items: 'code | visualaid visualchars visualblocks | spellchecker | fullscreen codesample' },
      insert: { title: 'Insert', items: 'image link media template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime' },
      format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat' },
      tools: { title: 'Tools', items: 'spellcheckerlanguage | code wordcount' },
      table: { title: 'Table', items: 'inserttable | cell row column | tableprops deletetable' },
      help: { title: 'Help', items: 'help' },
      // 自定义菜单
      export: { title: '导出', items: 'word pdf' }
      },
      // 工具栏图标
      toolbar1:'undo redo | formatselect | fontselect fontsizeselect lineheight | bold italic underline strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify removeformat | preview template codesample remove selectall link image fullscreen',
      toolbar2:'bullist numlist quicktable outdent indent | anchor restoredraft emoticons hr pagebreak searchreplace toc | help',
      // 自定义菜单按钮 https://www.tiny.cloud/docs/ui-components/menuitems/#howtocreatecustommenuitems
      setup: (editor) => {
      // 基本菜单
      editor.ui.registry.addMenuItem('word', {
        text: 'word',
        onAction: () => {
        // this.downWord();
        }
      });
      editor.ui.registry.addMenuItem('pdf', {
        text: 'pdf',
        onAction: () => {
        // this.downPdf();
        }
      });
      // 颜色列表列数
      color_cols: 4,
      // 撤销次数,默认无限次
      custom_undo_redo_levels: 30, 
      // 行高 5.5版本后支持
      lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 2',
      // 字体
      font_formats: 
            '宋体=simsun,serif;' +
            '仿宋=FangSong,serif;' + 
            '新宋体=NSimSun,serif;' + 
            '黑体=SimHei,serif;' + 
            '楷体=KaiTi,serif;' + 
            '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;' + 
            '隶书=LiSu,serif;' + 
            '幼圆=YouYuan,serif;' + 
            '华文细黑=STXihei,serif;' + 
            '华文楷体=STKaiti,serif;' + 
            '华文宋体=STSong,serif;' +
            // 默认字体
            'Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats',
      // 字号
      fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt', 
      // 如果表格border为0,TinyMCE会在编辑区内的表格周围添加虚线框作为视觉辅助
      visual: true,
      // 支持本地图片上传
      powerpaste_allow_local_images: true,
      // 粘贴为文本按钮的初始状态,开启后,只会粘贴文本内容
      paste_as_text: false,
      // 合并相同元素的内容
      paste_merge_formats: false,
      // 多少空格来表示HTML中的制表符
      paste_tab_spaces: 2,
      // 媒体实时预览开关 开启此选项后,用户可看到编辑区内嵌入视频的实时预览,而不是占位图, 此设置对video无效
      media_live_embeds: true,
      // 自定义媒体样式  http://tinymce.ax-z.cn/plugins/media.php
      video_template_callback: (data) => {
      return '<video width="' + data.width + '" height="' + data.height 
      + '"' + (data.poster ? ' poster="' + data.poster + '"' : '')
      + ' controls="controls">n' + '<source src="' + data.source1 + '"' 
      + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />n' 
      + (data.source2 ? '<source src="' + data.source2 + '"' 
      + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />n' : '') 
      + '</video>';
      },
      // 检查URL是否包含特殊内容,如包含则生成自定义的iframe,否则交给插件的默认逻辑生成默认代码
      media_url_resolver: (data, resolve) => {
      if (data.url.indexOf('YOUR_SPECIAL_VIDEO_URL') !== -1) {
        const embedHtml = '';
        resolve({html: embedHtml});
      }else{
        resolve({html: ''});
      }
      },
      // 分页
      pagebreak_separator: '<!-- my page break -->',
      // 拆分块元素
      pagebreak_split_block: true,  
      // 为编辑区锚点自定义样式 my-custom-class是样式名
      visual_anchor_class: 'my-custom-class',     
      // 为编辑区表格自定义样式
      visual_table_class: 'my-custom-class',
      // 自定义监听图片上传
      images_upload_handler: (blobInfo, succFun, failFun) => {
      let xhr;
      let formData;
      const file = blobInfo.blob();
      xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open(
        'POST',
        // 上传图片服务器地址
        'https://file.test.biz:4443/******',
      );
      xhr.onload = () => {
        let json;
        if (xhr.status !== 200) {
        failFun('HTTP Error: ' + xhr.status);
        return;
        }
        json = JSON.parse(xhr.responseText);
        // 这里是图片服务器返回的图片地址,需要根据实际情况自己处理
        succFun(
        'https://file.test.biz:4445/' +
          json.listData[0].cDirRelativePath +
          '/' +
          json.listData[0].cUpDocumentName,
        );
      };
      formData = new FormData();
      formData.append('file', file, file.name);
      // 将图片显示到富文本编辑器中
      xhr.send(formData);
      }
    };
  }
...
  1. 效果图
    在这里插入图片描述
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值