2

The available command setHTML replaces the existing content. Is there any way to insert HTML content at specific position as insertText.

Ganesh Matkam
  • 368
  • 1
  • 15

2 Answers2

1

After long research I found that currently there is no built-in way to get this done. However there is a workaround provided at Telerik forums.

Forum link: insert-html-content-to-editor

Example

public insertHTML(editor: EditorComponent) {
editor.exec('insertText', { text: '#CURSOR#' });
// Replace cursor placeholder with new HTML and set the new editor value.
editor.value = editor.value.replace(/#CURSOR#/, this.strResult);
}
Ganesh Matkam
  • 368
  • 1
  • 15
  • Also, it seems that there is an issue when trying to add a [custom Angular element](https://angular.io/guide/elements). E.g. `editor.exec("setHTML", "");` will work, while the `editor.exec("setHTML", "

    ");` won't work. Did you come across the issue?
    – Sasuke Uchiha Aug 31 '20 at 16:18
0

Alternatively,

import { DOMParser as ProseDOMParser } from "prosemirror-model";

public insertHTML(htmlString: string) {
    const view = this.editor.view;
    const state = view.state;

    const parser = new DOMParser();
    const tmpNode = parser.parseFromString(htmlString, 'text/html');

    const domParser = ProseDOMParser.fromSchema(schema);
    const newNodes = domParser.parse(tmpNode);

    view.dispatch(state.tr.insert(state.selection.head, newNodes));
}

The workaround by Telerik did not work for my custom schema properly, this one does.

Lukas Rotter
  • 4,158
  • 1
  • 15
  • 35