0

我尝试了几种方法使 quill-better-table 工作但没有成功,大多数示例都不适用于 Angular,我收到一条错误消息,提示“无法读取未定义的属性 'insertTable'”我将包括我的代码和错误如下,请帮助我。注意:这适用于生产中使用的应用程序。

这是我的 HTML 代码:

<div class="card">
  <div ibmGrid>
    <div ibmRow>
      <div ibmCol>
        <button ibmButton="secondary" size="sm" (click)="onInsertTable()">Add table</button>

        <form [formGroup]="editorForm" (ngSubmit)="onSubmit()">
          <div class="form-group">
            <quill-editor [styles]="editorStyle" [modules]="config" formControlName="editor" (onEditorCreated)="editorCreated($event)"></quill-editor>
          </div>
         
          <button ibmButton="primary">Save changes</button>
        </form>
      </div>
    </div>
</div>

这是我的 Angular TS 代码:

 import { Component, OnInit, AfterViewInit, ChangeDetectionStrategy } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DropdownModule, ModalService } from 'carbon-components-angular';
import * as quillBetterTable from 'quill-better-table';


interface Quill {
  getModule(moduleName: string);
}

interface BetterTableModule {
  insertTable(rows: number, columns: number): void;
}

// declare const require: any;
// let Quill: any = null;


@Component({
  selector: 'app-fnl-report',
  templateUrl: './fnl-report.component.html',
  styleUrls: ['./fnl-report.component.scss'],
  // changeDetection: ChangeDetectionStrategy.OnPush
})
export class FnlReportComponent implements OnInit {

  editorForm: FormGroup
  public quill: Quill;

  editorStyle = {
    height: '500px', 
    backgroundColor: '#fff'
  }

  config = {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],               // custom button values
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
      [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
      // [{ 'direction': 'rtl' }],                        // text direction
      [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],                                        // remove formatting button
      ['link']                                          // link and image, video ['link', 'image', 'video']  
    ]
  }

  constructor() { }

  ngOnInit() {
    this.editorForm = new FormGroup({
      'editor': new FormControl(null)
    });  
  }

  public editorCreated(event: Quill): void {
    this.quill = event;
    // Example on how to add new table to editor
    this.addNewtable();
  }

  private get tableModule(): BetterTableModule {
    return this.quill.getModule("better-table");
  }

  private addNewtable(): void {
    this.tableModule.insertTable(3, 3);
    console.log('Hi');
  }

  onSubmit() {
    console.log(this.editorForm.get('editor').value);
  }

  onInsertTable() {
    // const tableModule = this.quill.getModule('better-table');
    // tableModule.insertTable(3, 3);
  }

}

这是我的模块文件:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoadingModule, DropdownModule, GridModule, FileUploaderModule, DialogModule, ButtonModule } from 'carbon-components-angular';
import { Help16Module } from '@carbon/icons-angular/lib/help/16';
import { UploadFilesComponent } from './upload-files/upload-files.component';
import { FnlReportComponent } from './fnl-report/fnl-report.component';
import { ReactiveFormsModule } from '@angular/forms';
import { QuillModule, QuillConfig } from "ngx-quill";
import * as Quill from "quill";
import QuillBetterTable from "quill-better-table";


Quill.register(
  {
    "modules/better-table": QuillBetterTable
  },
  true
);

const quillConfig: QuillConfig = {
  modules: {
    table: false, // disable table module
    "better-table": {
      operationMenu: {
        items: {
          unmergeCells: {
            text: "Another unmerge cells name"
          }
        },
        color: {
          colors: ["#fff", "red", "rgb(0, 0, 0)"], // colors in operationMenu
          text: "Background Colors" // subtitle
        }
      }
    },
    keyboard: {
      bindings: QuillBetterTable.keyboardBindings
    }
  }
};


@NgModule({
  declarations: [
    UploadFilesComponent,
    FnlReportComponent
  ],
  imports: [
    CommonModule,
    LoadingModule,
    DropdownModule,
    GridModule,
    ButtonModule,
    FileUploaderModule,
    Help16Module,
    DialogModule,
    ReactiveFormsModule,
    QuillModule.forRoot(quillConfig)
  ],
  providers:[],
  exports: []
})
export class ImsHubModule { }

这是我为 quill 导入的 CSS:

@import '~quill/dist/quill.core.css';
@import '~quill/dist/quill.bubble.css';
@import '~quill/dist/quill.snow.css';

这是我对 quill 和 quill 表的 package.json 依赖项:

"dependencies": {
    "ngx-quill": "^13.0.1",
    "quill": "^1.3.7",
    "quill-better-table": "^1.2.10"
}

这是我得到的错误:

FnlReportComponent.html:24 ERROR TypeError: Cannot read property 'insertTable' of undefined
4

1 回答 1

1

不幸的是,您不能将 quill-better-table 与 ngx-quill 包装器一起使用。ngx-quill 仍然基于 quilljs v1。quill-better-table 需要 quilljs v2.0.0-dev.3。您可以在“要求”部分阅读相关内容:这里

我可以与您分享我是如何在我的案例中实现简单的粘贴和读取表格的。它受到 本文的启发,并使用自定义块创建。而且它不是向羽毛笔添加元素的正确方法。但是我们在内部使用编辑器,所以我们确信它是安全的。

  1. 像这样创建一个新的“块嵌入”:
import Quill from 'quill';
const BlockEmbed = Quill.import('blots/block/embed');

    export class TableBlockEmbed extends BlockEmbed {

      static blotName = 'TableBlockEmbed';
      static tagName = 'table';

      static create(value) {
        const node = super.create();
        let valueToReturn = value;
        if (!value.includes('assignedTableId')) {
          const tableId = `assignedTableId-${Date.now()}`;
          valueToReturn = value
            .replace('#tableId', `#${tableId}`)
            .replace('table-layout: fixed;', '');
          node.setAttribute('id', tableId);
        } else {
          const existedId = valueToReturn.match(/#assignedTableId-(\d+)/i)[1];
          node.setAttribute('id', `assignedTableId-${existedId}`);
        }
        node.innerHTML = this.transformValue(valueToReturn);
        return node;
      }

      static transformValue(value) {
        let handleArr = value.split('\n');
        handleArr = handleArr.map(e => e.replace(/^[\s]+/, '')
          .replace(/[\s]+$/, ''));
        return handleArr.join('');
      }

      static value(node) {
        return node.innerHTML;
      }
    }
  1. 在使用 ngx-quill 的组件的构造函数中运行新嵌入块的注册:
constructor() {
    Quill.register(TableBlockEmbed, true);
  }
  1. 添加编辑器在下面创建了此代码。(您当然可以在此处添加/删除所需的样式。例如,我添加了margin: 0 auto !important;因为我想强制表格始终居中):
onEditorCreated(quill: Quill): void {
    quill.clipboard.addMatcher('TABLE', (node, delta) => {
      const Delta = Quill.import('delta');
      const tableTagStyles = node.getAttribute('style');
      return new Delta([
        {
          insert: {
            TableBlockEmbed:
              `<style>#tableId {${tableTagStyles} margin: 0 auto !important; }</style>` + delta.ops[0].insert.TableBlockEmbed
          }
        }
      ]);
    });
  }
  1. 我还添加了一些样式:
quill-view,
quill-editor{
  ::ng-deep {
    table {
      width: 100%; // if table has no width - then give it by default 100%
      max-width: 100% !important;
      box-sizing: border-box;
    }
  }
}

我知道这个解决方案只是解决方法,但在等待基于 quill 2 的 ngx-quill 之前,我至少能够在编辑器中提供粘贴表格的功能,这看起来相当不错。

例子:

办公室词表:

在此处输入图像描述

ngx-quill 中的表:

在此处输入图像描述

excel中的表格:

在此处输入图像描述

ngx-quill 中的表:

在此处输入图像描述

于 2021-03-22T17:34:58.450 回答