angular引入富文本ngxquill自定义图片上传解决Cant-resolve-quill

23次阅读

共计 2127 个字符,预计需要花费 6 分钟才能阅读完成。

1. 安装依赖


npm i ngx-quill
npm i quill

ps:一定要安装 quill,不然 ngx-quill 会报 Can't resolve'quill' in xxxx, 因为ngx-quill 内部引用了quill

2. 使用


1. 引用

/* 在自己的 `NgModule` 的 `imports` 里面引用,我是在 `RoutesModule` 里引用的 */
import {QuillModule} from 'ngx-quill';
@NgModule({
  imports: [
    ...
    QuillModule.forRoot()
    ...
  ]
})

2. 使用组件

/* 直接使用 */
<quill-editor></quill-editor>

/* 模板绑定 */
<quill-editor [(ngModel)]="content"></quill-editor>

/* 响应式表单 */
<quill-editor formControlName="content"></quill-editor>

点击查看 quill 配置地址

3. css 样式引用

/* 在 index.html 页面上引用 */
<link href="https://cdn.quilljs.com/1.2.2/quill.snow.css" rel="stylesheet">

点击查看其他 css 版本

3. 自定义图片上传


给组件添加 onEditorCreated 方法,获取 quill 对象,并绑定自定义图片上传函数

html:
<quill-editor  (onEditorCreated)="EditorCreated($event)"></quill-editor>

ts:
  // 富文本初始化钩子函数
  EditorCreated(quill: any) {
    // 获取 quill 的工具栏对象
    const toolbar = quill.getModule('toolbar');
    // 给工具栏的 image 功能添加自定义函数,注意 this 指向问题
    toolbar.addHandler('image', this.imageHandler.bind(this));
    // 保存 quill 对象
    this.editor = quill;
  }
  // 自定义图片上传功能
  // 创建一个 input 对象来实现上传,除了下面的自定义代码区域,其他为官方代码
  imageHandler() {const Imageinput = document.createElement('input');
    Imageinput.setAttribute('type', 'file');
    Imageinput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp'); // 可改上传图片格式
    Imageinput.classList.add('ql-image');
    Imageinput.addEventListener('change', () => {const file = Imageinput.files[0];
      if (Imageinput.files != null && Imageinput.files[0] != null) {
          /* 自定义代码 */
          .......
          .......
          // 下面这句话必填,成功后执行(imageUrl 为上传成功后的图片完整路径)this.editor.insertEmbed(this.editor.getSelection(true).index, 'image', imageUrl);
      }
    });
    Imageinput.click();}

无注释复制粘贴版本

html:
<quill-editor  (onEditorCreated)="EditorCreated($event)"></quill-editor>

ts:
  EditorCreated(quill: any) {const toolbar = quill.getModule('toolbar');
    toolbar.addHandler('image', this.imageHandler.bind(this));
    this.editor = quill;
  }
  imageHandler() {const Imageinput = document.createElement('input');
    Imageinput.setAttribute('type', 'file');
    Imageinput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp');
    Imageinput.classList.add('ql-image');
    Imageinput.addEventListener('change', () => {const file = Imageinput.files[0];
      if (Imageinput.files != null && Imageinput.files[0] != null) {
          .......
          this.editor.insertEmbed(this.editor.getSelection(true).index, 'image', 图片完整路径);
      }
    });
    Imageinput.click();}

正文完
 0