如何在angular项目中使用Editor.md

谷梁德容
2023-12-01

editor.md是国内开源的一款在线Markdown编辑器,可嵌入的 Markdown 在线编辑器(组件),基于 CodeMirror、jQuery 和 Marked 构建。

GitHub:https://github.com/pandao/editor.md

安装依赖

# npm
 npm install jquery
 # yarn
 yarn add jquery

资源下载

下载editor.md的的文件,并放置到assets文件夹中,如src/assets/editor.md/
也可以通过 NPM 安装:

npm install editor.md

或者通过 Bower 安装:

bower install editor.md

本文后面讲的是直接下载文件资源方式。

配置

angular.json中的build中配置editor.md的css和js路径

"styles": [
   "src/assets/md_editor/css/editormd.css",
   "src/assets/md_editor/lib/codemirror/codemirror.min.css",
 ],
"scripts": [
   "./node_modules/jquery/dist/jquery.js",
   "src/assets/md_editor/lib/flowchart.min.js",
   "src/assets/md_editor/lib/jquery.flowchart.min.js",
   "src/assets/md_editor/js/editormd.min.js",
   "src/assets/md_editor/lib/codemirror/codemirror.min.js",
   "src/assets/md_editor/lib/marked.min.js",
   "src/assets/md_editor/lib/prettify.min.js",
   "src/assets/md_editor/lib/underscore.min.js",
   "src/assets/md_editor/lib/raphael.min.js",
   "src/assets/md_editor/lib/sequence-diagram.min.js"
 ]

在app文件下创建一个editor文件夹,在里面创建一个编辑器配置文件editor-config.ts

  • editor-config.ts
declare var $: any;
declare var editormd: any;

export class EditorConfig {
  // public width = '100%';
  public width = '868';
  public height = '558';
  public path = './assets/md_editor/lib/';
  public codeFold: true;
  public placeholder = '请输入正文内容'; // 输入提示
  public searchReplace = true;
  public toolbar = true;
  public emoji = false; // 关闭外部emoji工具
  public taskList = true;
  public tex = true;// 数学公式类默认不解析
  public readOnly = false;
  public tocm = true;
  public watch = false; // 是否右边展示实时预览
  public previewCodeHighlight = true;
  public saveHTMLToTextarea = true; // 保存HTML到Textarea中
  public markdown = '';
  public flowChart = true;//流程图
  public syncScrolling = true;
  public sequenceDiagram = true;//UML时序图
  public imageUpload = true;
  public imageFormats = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'webp'];
  // public crossDomainUpload = true;
  // public imageUploadURL = ''; // 上传图片的接口
  // public htmlDecode = 'style,script,iframe';    
  // public uploadCallbackURL = ""
  public htmlDecode = "style,script,iframe,sub,sup|on*"; // 开启HTML标签解析,可以过滤html的标签解析,为了安全性,默认不开启

  public toolbarIcons = function () {
    // Or return editormd.toolbarModes[name]; // full, simple, mini
    // Using "||" set icons align right.
    return [ "bold","italic","h1","h2","del","|","list-ul","list-ol","hr","quote","code-block","table","link","watch","|","fullscreen","file","imageUpload","|","undo","redo",]
  };
  public toolbarIconsClass = {
    imageUpload: "fa-file-image-o",// 指定一个FontAawsome的图标类
  };
  public toolbarIconTexts = {
    // 如果没有图标,则可以这样直接插入内容,可以是字符串或HTML标签
    // file: `<div><input type="file" name="file" id="uploadImage" class="inputfile" style="position:absolute;opacity:0;" accept="image/png,image/jpeg,image/gif,image/jpg,image/svg" /> 
    // <label for="file" style="cursor:pointer;">上传文件</label></div>`
  };

  // 自定义工具栏按钮的事件处理
  public toolbarHandlers = {
    /**
     * @param {Object}      cm         CodeMirror对象
     * @param {Object}      icon       图标按钮jQuery元素对象
     * @param {Object}      cursor     CodeMirror的光标对象,可获取光标所在行和位置
     * @param {String}      selection  编辑器选中的文本
     */
    imageUpload: function (cm, icon, cursor, selection) {
      // deal upload event
      $('#uploadImage').click();
      $('#uploadImage').unbind().bind("change", e => {
        let fd = new FormData();
        // 添加到fd对象中等待提交
        fd.append("files", e.target['files'][0]);
        if(!fd) return;
        $.ajax({
          type: 'post',
          url: '/api/v1/upload',
          data: fd,
          cache: false,
          contentType: false,
          processData: false,
          success: data => {
            if (data && data.length > 0) {
              // cm.replaceSelection("![](http://10.0.10.7:10020" + data[0] + ")" + selection);
              // 生产环境使用相对路径
              cm.replaceSelection("![](" +  data[0] + ")" + selection);
            }
          }
        })
      })
      console.log("imageUpload =>", icon.html());
    },
  };

  // 用于增加自定义工具栏的功能,可以直接插入HTML标签,不使用默认的元素创建图标
    public toolbarCustomIcons =  {
      file: `<input type="file" name="file" id="uploadImage" class="inputfile" style="position:absolute;opacity:0;" accept="image/png,image/jpeg, image/gif,image/jpg,image/svg,image/xbm,image/pgm,image/xpm" /> `
  };
  public lang = {
    toolbar: {
      imageUpload: "图片上传",  // 自定义按钮的提示文本,即title属性
    }
  };

  public editorFunction = '';//定义调用的方法
  constructor() { }
}

在具体组件中使用

  • html
<div id="markdown" >
   <textarea id="editText" style="display: block;"></textarea>
</div>
  • ts
import { EditorConfig } from 'xxx/editor-config';//config文件所在路径

editor:any;
conf = new EditorConfig();
showInfo:string;//编辑器内容

constructor(){}

ngAfterViewInit(): void {
    this.createEditor();
}

createEditor(){
    this.editor = editormd("markdown", this.conf); // 创建编辑器
    // //解决右侧预览偶尔显示不出来的问题(编辑功能下的md)
    $("#markdown.editormd-preview-container")[0].innerHTML = this.showInfo;
    // 在没有开预览模式下获取编辑状态下的值
   // let iputData = $('#markdown .editormd-markdown-textarea').val();
   // 编辑器事件监听
    this.editor.on('change', ()=> {
      const textarea = $("#editText");
      const value= {
        textarea:textarea.val()
      }
      this.showInfo= value.textarea
    });
  }

注意: 由于editor.md编辑器中自带一些图片和emoji资源,需要从github或者外网加载过来,这样就会对网页性能有一些影响,有需要可以考虑在样式文件中替换掉。还有一些加载空表格和图片上传组件的问题,这里就不赘述了。

 类似资料: