Search code examples
node.jsangulartypescriptquill

How do you initialize a Quill Editor in an Angular 2 Component?


I am trying to implement my own Quill editor component in my Angular 2 project. I used npm to install quill into my project. I am trying to create a word counter application with my component. I am trying to implement the code from :https://quilljs.com/blog/building-a-custom-module/

HTML Code:

<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;
}

This is my Component code:

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
            }
          });
  }
}

When I serve my application, I receive:

quill Invalid Quill container #editor

Solution

  • You can check Angular lifecycle and invoke your Quill-related stuff there, putting them in constructor() might cause error since the HTML elements are not yet rendered.

    You can try putting them in ngOnInit() or ngAfterViewInit()

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

    Reference : https://angular.io/guide/lifecycle-hooks

    4th March 2019

    Another approach that can be done for this are :

    • If you element is a ViewChild , then using the Lifecycle as above should help
    • If you would like your current element to be the editor , trying inject ElementRef might do as well