angular引入富文本ngx-quill,自定義圖片上傳(解決Can't resolve 'quill')

1. 安裝依賴


npm i ngx-quill
npm i quill

ps:必定要安裝 quill ,否則ngx-quill會報Can't resolve 'quill' in xxxx, 由於ngx-quill內部引用了quillcss

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配置地址html

3. css 樣式引用

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

點擊查看其餘css版本npm

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();
  }
相關文章
相關標籤/搜索