0

So I am implementing a text auto-complete feature inside the Quill Editor for Angular. Currently, I have a function called autoComplete() that appends a dummy text for testing purposes to the ngModel variable for my Quill editor. I first check if htmlText (the ngModel variable) has contents, check if its actual content without the HTML tags is greater than 10 (so auto-completion until a couple words are written), and checks if it has auto-completed before too (is there a span of extra text?)

autoCorrect(): void {
    if (this.htmlText && stripHTML(this.htmlText).length > 10 && !this.htmlText.includes("<span")){
      if (this.htmlText.endsWith("</p>")){
      let pos = this.htmlText.indexOf("</p>")
      this.autocorrectText = this.htmlText.slice(0,pos) + "<span style=\"color: rgb(187, 187, 187);\">" + " finds you well" + "</span>" + this.htmlText.slice(pos);
      this.htmlText = this.autocorrectText;
      let range = this.editor.quillEditor.getSelection();
      this.editor.quillEditor.insertText(range!.index, this.autocorrectText, 'bold', true);
      }

But the problem is it works with this dummy data using this way but the cursor moves back to the beginning of the text editor

If I try to implement it using the getSelection and insertText functions as I have found on StackOverflow, using the last two lines of code above, it says

ERROR TypeError: Cannot read properties of undefined (reading 'quillEditor')

I define quillEditor like this inside my typescript file:

@ViewChild('editor') editor!: QuillEditorComponent

It seems this code above is not getting a reference to my initiated quill editor.

The desired behavior is that the cursor would stay in between the typed text and the auto-completed text that is suggested. Similar to GMail for instance.

Any ideas are much appreciated.

1 Answers1

0

I was getting the same error and confusion after I figured it out that to get the reference to the editor you should do it in OnEditorCreated property:

<quill-editor
  #editor
  [formControl]="control"
  [placeholder]="''"
  [styles]="{ 'min-height': '120px' }"
  [modules]="modules"
  (onEditorCreated)="onEditorCreated($event)"
  (onEditorChanged)="onEditorChanged($event)"
>
</quill-editor>

and then in your component:

onEditorCreated(quill: any): any {
  this.quillEditor = quill;
  this.quillEditor.insertText(this.quillEditor.getSelection()?.index, tag);
}

This is because the editor take a time to initialize itself so it's necessary to get the reference in onEditorCreated listener.

maycol99
  • 3
  • 3