Search code examples
javascriptangulartinymcetinymce-4

Insert text at cursor using tinyMCE and Angular


Using tinyMCE with Angular I need to insert text at the cursor position, preferably with a toolbar button.

As I understand, I'll need to use the onExecCommand event with mceInsertContent command.

I've looked at the following:

But the solutions don't help in this case.

Here's the documentation

editor-dialog.component.html

<editor [init]="tinyMceConfig"
  [formControl]="data.formControl">
</editor>

editor-dialog.component.ts

/* ... */

export class EditorDialogComponent implements OnInit {
  tinyMceConfig: any;

  constructor(
    /* ... */
  ) { }

  ngOnInit() {
    this.configureTinyMce();
  }

  configureTinyMce() {
    this.tinyMceConfig = {
      theme: 'modern',
      menubar: false,
      branding: false,
      height: 400,
      skin_url: 'assets/tinymce/skins/lightgray',
      inline: false,
      plugins: [
        'advlist lists link image directionality',
        'searchreplace visualblocks visualchars media table contextmenu paste textcolor colorpicker pagebreak code'
      ],
      // tslint:disable-next-line:max-line-length
      toolbar: 'copy undo redo formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat hr pagebreak code',
      image_advtab: true,
      imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions',
      paste_data_images: !0,
      importcss_append: !0,
      images_upload_handler: function (e, t, a) {
        console.log('image');
        t('data:' + e.blob().type + ';base64,' + e.base64());
      },
    };
  }
}

Thanks


Solution

  • The documentation you referenced is how to get TinyMCE integrated in an Angular application. What I believe you want to do is:

    1. Add a toolbar button to the toolbar
    2. Clicking the toolbar button inserts content at the current cursor location

    Fundamentally the fact that you are using Angular is not important to either of these goals so you won't see anything Angular specific in the following details.

    Adding a Toolbar Button

    This is done (in TinyMCE 5) via the tinymce.editor.ui.registry.addButton() API. This is documented here: https://www.tiny.cloud/docs/api/tinymce.editor.ui/tinymce.editor.ui.registry/#addbutton

    Inserting Content at the Cursor

    This is done (in TinyMCE 5) via the tinymce.editor.insertContent() API. This is documented here: https://www.tiny.cloud/docs/api/tinymce/tinymce.editor/#insertcontent

    The simplest way to do all of this is to use your TinyMCE configuration via the setup() function. You can add the button and determine what actions (via JavaScript) it will take when clicked all in one place.

    Here is an example: http://fiddle.tinymce.com/fHgaab