LAZ
LAZ

Reputation: 534

Create svelte component on every click

I'm trying to create new instances of the same component in svelte whenever a button or other action happens on the page, without having to make a list and {each} over them. I just want to do something like new Component(some context data) and forget. Another concern is I don't want the component to disappear when the parent is removed.

Thank you

Upvotes: 1

Views: 626

Answers (1)

brunnerh
brunnerh

Reputation: 184376

Just mount it straight on the document.body:

new Component({ target: document.body })

But be aware that if you do not $destroy it yourself, you will end up with a memory leak.

When I do something like this, e.g. for notifications, I dispatch an event from the component that tells the calling code when the component can safely be destroyed. Something like:

const notification = new Notification({ target: document.body, ... });
notification.$on('close', () => notification.$destroy());

Upvotes: 2

Related Questions