'CKEditor 5 - insert text

Is it possible to insert text into the editor at current selection?

I have tried

import Text from '@ckeditor/ckeditor5-engine/src/model/text';

function insertText() {
  let text = new Text('test');
  ckEditor.model.insertContent(text, ckEditor.model.document.selection);
}

where ckEditor is the editor object returned from ClassicEditor.create

code runs without error, but nothing happens

I have managed to get similar code to work from within a plugin, but here I am trying to inject the text from the host app



Solution 1:[1]

That worked for me, using the editor returned by (ready):

insertTag(tag: string) {
  const insertPosition = this.editor.model.document.selection.getFirstPosition();
  const viewFragment = this.editor.data.processor.toView(`<p>${tag}</p>`);
  const modelFragment = this.editor.data.toModel(viewFragment);
  this.mod.insertContent(modelFragment);
}

See also the the font.

Solution 2:[2]

Just to add, to enable the input focus after inserting the text, add this code.

editor.editing.view.focus()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gleitonfranco
Solution 2 Mohammad Syuhada