How can i set character limit in quill editor

Niraj Bharti picture Niraj Bharti · Mar 15, 2017 · Viewed 11.1k times · Source

I am using Quill Editor in angular 2, and want to limit the user to enter maximum 1000 char.

Answer

jgranstrom picture jgranstrom · Mar 15, 2017

There is as far as I know no built in configuration for that. You can however delete input that exceeds a certain length.

Example code from this github issue

const limit = 1000;

quill.on('text-change', function (delta, old, source) {
  if (quill.getLength() > limit) {
    quill.deleteText(limit, quill.getLength());
  }
});

It is not clear if you are using pure quill or something like ngx-quill so I cannot provide a full example. Provide more details if you want additional help with integrating it in angular.

Remember to to quill.off(...) for your text-change handler on ngOnDestroy to prevent leaks.

Edit

Solution added using the ngx-quill module.

Editor component

editor.component.ts

import { Component } from '@angular/core';

const MAX_LENGTH = 10;

@Component({
  selector: 'editor',
  templateUrl: './editor.component.html',
})
export class EditorComponent {
  /*
   * Delete added characters that exceeds max length
   */
  textChanged($event) {
    if ($event.editor.getLength() > MAX_LENGTH) {
      $event.editor.deleteText(MAX_LENGTH, $event.editor.getLength());
    }
  }
}

Editor template

editor.template.html

<quill-editor (onContentChanged)="textChanged($event)"></quill-editor>