How can I add html tag to the content div of Quill text editor in Angular?

10.1k Views Asked by At

I have a form with quill text editor.

<quill-editor [modules]="quillConfig" (onEditorCreated)="getEditorInstance($event)"></quill-editor>

I have an image gallery in a modal, which is filled with my images, and I would like that, if I select an image from modal put the img tag after the text in the editor.

This is the code of one image what I want to add:

<div class="news-image-box">
  <img src="${image.path}" alt="${image.description}">
  <div class="row">
    <div class="col-md-9"><p>${image.description}</p></div>
    <div class="col-md-3 news-image-credit"><p>${image.credit}</p></div>
  </div>
</div>

My problem is that the contenteditable div of Quill (which is the div for my text and it has "ql-editor" css class) is generated, so I can't give a local reference for using @ViewChild... (or I don't know how)

document.getElementsByClassName('ql-editor')[0].innerHTML += imageElement;

I tried to get the content of "ql-editor" div by a sample getElementsByClassname and just added my img tag to it, but the angular throws this error:

core.js:1673 ERROR TypeError: Cannot read property 'emit' of undefined
at Scroll.update (quill.js:4329)
at MutationObserver.<anonymous> (quill.js:7118)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3820)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runGuarded (zone.js:151)
at MutationObserver.<anonymous> (zone.js:129)

I works with just a string btw...

document.getElementsByClassName('ql-editor')[0].innerHTML += 'something';
2

There are 2 best solutions below

13
On BEST ANSWER

You can go with ngModel, it is clearly mentioned in documentation. Reference: ngx-quill git Repo

Example Snippet:

 <quill-editor [(ngModel)]="productDetail"  [style]="{border: '0px'}"></quill-editor>
1
On

If I understand your problem, you want to add a img tag inside your quill-editor.

Modifying the Element.innerHTML property is a good method if you want to do this but is a bit complicated. It exists simplier method to do that like Element.insertBefore() or Element.append().

You can use them like this :

document.getElementsByClassName('ql-editor')[0].append(imageElement);

Or

document.getElementsByClassName('ql-editor')[0].insertBefore(imageElement, null);

If you really want to use the Element.innerHTML, I invite you to see the documentation about this property.

Hope this helps

Edit: Grammar