sveltesurveyjs

How to use SurveyJS Custom Item Template in Svelte?


In the documentation JS example JSX syntax is used which doesn't seem to be easily transferred to a .svelte file..?

The vue example registers a component

// main.js
const app = createApp(App);
app.component("ranking-item-template", CustomRankingItem);

But I don't think there's an equivalent in Svelte? Is there a way to use a Svelte Component or a Web Component?


Solution

  • One of the other examples shows DOM manipulation as an approach.

    You could add an event listener and mount a Svelte component that way:

    import { mount } from "svelte";
    import Item from "./item.svelte";
    
    // ...
    const survey = new Survey.Model(json);
    survey.onAfterRenderQuestion.add(onAfterRenderQuestion);
    
    function onAfterRenderQuestion(_, options) {
      options.htmlElement
        .querySelectorAll('.sv-string-viewer')
        .forEach(el => {
          const choice = el.textContent;
          el.innerHTML = '';
          mount(Item, { target: el, props: { choice } });
        });
    }