2

我正在使用 Angular 和 ngx-quill。我有一个自定义工具栏按钮,它将插入具有某些属性的文本。我想在单击该文本时选择该文本。

这是我到目前为止所拥有的:

export class InsertDemographic extends Embed {
  static blotName: string = "demographic";
  static tagName: string = "span";
  static className: string = "demographic";

  static create(demographic: Demographic) {
    let node = super.create();
    node.setAttribute('data-demographic_id', demographic.id);
    node.innerHTML = `[${demographic.name.replace(" ","_")}]`;
    node.addEventListener("click", () => {
        console.log(this);
        /* const range = this.quill.getSelection(true);
        this.quill.setSelection(range.index - 1, 1, 'user'); */
    });
    
    return node;
  }

  static value(node){
    return {
        name: node.textContent.replace(/[\[\]]/g,""),
        id: node.dataset.demographic_id
    } as Demographic;
  }
}

我添加了一个单击事件侦听器,它应该获取当前的 quill 实例以获取和设置选择。注释代码可以工作,但我不知道如何获取 quill 实例!

目前,此代码位于与我的编辑器组件分开的文件中,该组件扩展了工具栏并映射了自定义图标等。这个位于组件外部的单独文件使得管理 quill 实例变得困难,不确定正确的方法是什么。

4

1 回答 1

2

简短的回答

Quill这是从任何子节点获取实例的实用方法:

function findQuill(node) {
  while (node) {
    const quill = Quill.find(node);
    if (quill instanceof Quill) return quill;
    node = node.parentElement;
  }
}

长答案

有时尝试Quill从印迹本身访问实例可能感觉像是在与 Quill 战斗,这有点反模式。有时,更“Quill-y”的做事方式可能是使用模块:

import Module from 'quill/core/module';

export class Demographics extends Module {
  constructor(quill, options) {
    super(quill, options);
    quill.root.addEventListener('click', (event) => this.handleClick(event));
  }

  handleClick(event) {
    const node = event.target;
    const demographic = node.closest('.demographic');
    if (!demographic) return;
    const blot = Quill.find(node);
    const index = this.quill.getIndex(blot);
    const length = blot.length();
    this.quill.setSelection(index, length);
  }
}

我已经整理了一个工作示例strong为简单起见处理标签)。

于 2021-05-18T06:46:33.803 回答