Angular:ngx-quill富文本编辑器的使用

首先在Angular6项目中安装富文本编辑器的依赖

1、angular >= 5时ngx-quill的安装:

npm install ngx-quill

2、angular < 5时:

npm install [email protected]

然后在使用到富文本编辑器的模块中,引入ngx-quill的QuillModule

例如:在message-management.module.ts中引入:

import { NgModule } from '@angular/core';
import { MessageRoutingModule, MessageComponents } from './message-management-routing.module';
import { SharedModule } from '../../../../shared/shared.module';
//  import zorroAnt
import { NgZorroAntdModule } from 'ng-zorro-antd';
import { QuillModule } from 'ngx-quill';                 // 引入富文本编辑器模块
import { PublishNewsProvider } from '../../../../providers/business/message-center/publish-news/publish-news-provider';
import { MesManagementProvider } from '../../../../providers/business/message-center/mes-management/mes-management-provider';


@NgModule({
  imports: [
    MessageRoutingModule,
    NgZorroAntdModule,
    SharedModule,
    QuillModule                                      // 富文本编辑器模块
  ],
  declarations: [
    ...MessageComponents
  ],
  providers: [
    PublishNewsProvider,
    MesManagementProvider
  ]
})
export class MessageManagementModule { }

 在index.html中添加quill的样式注意这里一定要填写你安装的quill版本!否则会找不到文件报错404。不知道安装的版本的去package.json中找quill版本信息——这里我安装的是1.3.6版本):

接下来在组件和页面中使用富文本编辑器

页面上添加如下代码,就可以在当前页面展示出富文本编辑器:

 

展示效果如下: 

Angular:ngx-quill富文本编辑器的使用_第1张图片

组件中富文本编辑器生成的内容绑定的字段为content(参见上面HTML代码中使用[(ngModel)]="content"进行绑定):

/**
   * ngx-quill上传图片需要的方法
   */
  EditorCreated(quill) {
    const toolbar = quill.getModule('toolbar');
    toolbar.addHandler('image', this.imageHandler.bind(this));
    this.editor = quill;
  }

  /**
   * ngx-quill上传图片需要的方法
   */
  imageHandler() {
    const Imageinput = document.createElement('input');
    Imageinput.setAttribute('type', 'file');
    Imageinput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
    Imageinput.classList.add('ql-image');
    Imageinput.addEventListener('change', () => {
      const file = Imageinput.files[0];
      const data: FormData = new FormData();
      data.append('file', file, file.name);
      const headers = new HttpHeaders();
      headers.append('Accept', 'application/json');
      const headerOptions = { headers: headers };
      if (Imageinput.files != null && Imageinput.files[0] != null) {
        this.http.post(this.image_upload_url, data, headerOptions)
          .subscribe(res => {
            const range = this.editor.getSelection(true);
            const index = range.index + range.length;
            this.editor.insertEmbed(range.index, 'image', _.get(res, 'data', ''));
          });
      }
    });
    Imageinput.click();
  }


  /**
  * 富文本编辑器quill-editor内容变化时change事件
  */
  contentChanged(event) {
    this.content = event.html;  // 内容编辑
  }

更多用法参考:https://www.cnblogs.com/scott-j/p/9016027.html

你可能感兴趣的:(前端开发,Angular6,Angular6基础学习)