Image URL References using PrimeNG Editor

Permalink | Tags:  development
Posted: Thursday, 01 June 2017
Share:  

Under the covers the PrimeNG Editor uses Quill (https://quilljs.com), which is a JavaScript WYSIWYG editor. Quill itself has a shortcoming in that it only allows you to insert Base64 encoded images directly into the HTML source by default.

To change this behaviour you can get a reference in the page to Quill and then override the Image button handler, however in Angular 2 we need to do this in the controller which is a bit different (though not much).

In the controller create an event handler for the PrimeNG Editor's onInit event, which at its most basic will be a prompt:

editorInit(event) {
  const quill = event.editor;
  const toolbar = quill.getModule('toolbar');
  toolbar.addHandler('image', () => {
    const range = quill.getSelection();
    const value = prompt('What is the image URL');

    quill.insertEmbed(range.index, 'image', value, '');
  });
}

 

Then in the view add the event handler to the control:

<p-editor name="content" formControlName="content"
    [style]="{'height':'320px'}" (onInit)="editorInit($event)"
    placeholder="Content">

Now when you click the Insert Image button, you should be shown a prompt, which you can now replace with anything you like to capture the URL.