【问题标题】:How do you initialize a Quill Editor in an Angular 2 Component?如何在 Angular 2 组件中初始化 Quill 编辑器?
【发布时间】:2017-12-22 11:01:25
【问题描述】:

我正在尝试在我的 Angular 2 项目中实现我自己的 Quill 编辑器组件。我使用 npm 将 quill 安装到我的项目中。我正在尝试使用我的组件创建一个单词计数器应用程序。我正在尝试实现代码:https://quilljs.com/blog/building-a-custom-module/

HTML 代码:

<div id="editor"></div>
<div id="counter">0</div>

CSS:

body {
  padding: 25px;
}

#editor {
  border: 1px solid #ccc;
}

#counter {
  border: 1px solid #ccc;
  border-width: 0px 1px 1px 1px;
  color: #aaa;
  padding: 5px 15px;
  text-align: right;
}

这是我的组件代码:

import { OnInit, Component, ViewChild, ElementRef } from '@angular/core';

import * as Quill from 'quill';

@Component({
  selector: 'app-quill-editor',
  templateUrl: './quill-editor.component.html',
  styleUrls: ['./quill-editor.component.css']
})
export class QuillEditorComponent{
// Implement and register module

  constructor()
  {
          Quill.register('modules/counter', function(quill, options) {
            var container = document.querySelector('#counter');
            quill.on('text-change', function() {
              var text = quill.getText();
              // There are a couple issues with counting words
              // this way but we'll fix these later
              container.innerHTML = text.split(/\s+/).length;
            });
          });

          console.log(document.querySelector('#editor'))

          // We can now initialize Quill with something like this:
          var quill = new Quill('#editor', {
            modules: {
              counter: true
            }
          });
  }
}

当我提交申请时,我会收到:

quill Invalid Quill container #editor

【问题讨论】:

    标签: node.js angular typescript quill


    【解决方案1】:

    您可以检查 Angular 生命周期并在那里调用与 Quill 相关的东西,将它们放在 constructor() 中可能会导致错误,因为 HTML 元素尚未呈现。

    您可以尝试将它们放入 ngOnInit() 或 ngAfterViewInit()

    export class QuillComponent implements OnInit {
        constructor() {
        }
    
        ngOnInit() { // Quill initialization and querying for elements here }
    }
    

    参考:https://angular.io/guide/lifecycle-hooks

    2019 年 3 月 4 日

    为此可以采取的另一种方法是:

    • 如果您的元素是 ViewChild ,那么使用上述生命周期应该会有所帮助
    • 如果您希望当前元素成为编辑器,尝试注入 ElementRef 也可以

    【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多