How to include and use tinymce in a svelte component?

Viewed 775

I want to include an external rtf component in my svelte app.

I tried adding tinymce using the cdn in template.htm and then creating the following svelte component. The editor renders, however I can't get data into or out of the editor.

<script>
  import { onMount, tick } from 'svelte'
  export let label = ''
  export let value = ''

  $: console.log('value', value)

  onMount(() => {
    tinymce.init({
      selector: '#tiny',
    })
  })
</script>

<p>
  <label class="w3-text-grey">{label}</label>
  <textarea id="tiny" bind:value />
</p>
2 Answers

Super old but encountered this today and found a solution.

Solution:

<svelte:head>
    <script src="https://cdn.tiny..."></script>
</svelte:head>

<script>
import {onMount} from 'svelte';
let getHTML;
let myHTML;
onMount(() => {
    tinymce.init({
        selector: '#tiny'
    })

    getHTML = () => {
        myHTML = tinymce.get('tiny').getContent();
    }
})
</script>

<textarea id="tiny" bind:value />

<!-- click to get html from the editor -->
<button on:click={getHTML}>Get HTML from TinyMCE</button>
<!-- html is printed here -->
{myHTML}

Explanation:

My initial thought was to bind per normal with

<textarea bind:value></textarea>

but that doesn't work I think because tinyMCE is doing complicated stuff in the background. Instead of adding the cdn reference in template.htm I used <svelte:head> so it only is loaded for this component. The function tinymce.get('...').getContent() must be called to get the contents of the editor, but it requires tinyMCE, so it must be called within the onMount. So I define a function getHTML within onMount. Now getHTML can be used anywhere to assign the contents of the editor to myHTML.

step one:

run this command on in your terminal

    npm install @tinymce/tinymce-svelte

(reference for installation : https://www.tiny.cloud/docs/integrations/svelte/)

step two :

  <script>
    import { onMount } from 'svelte';
    let myComponent;
    let summary='';  

   
    onMount(async()=>{
            const module=await import ('@tinymce/tinymce-svelte');
            myComponent=module.default;
    })
  </script> 

step three :

<svelte:component this={myComponent} bind:value={summary}/>
{@html summary}
Related