I have a svelte component for Address and user can add multiple addressees (primary, secondary, other etc) by clicking a button. I dont know upfront how many addresses user will add. I am struggling to model this with Svelte. The closest thing I have found is svelte:component but that only allows loading one component at a time.
Add a comment
|
1 Answer
You could keep all the addresses in an array and render an Address component for each element in this array and keep the element updated with e.g. an event emitted from the component.
Example (REPL)
<!-- App.svelte -->
<script>
import Address from './Address.svelte';
let addresses = [''];
function addAddress() {
addresses = [...addresses, ''];
}
function changeAddress(address, index) {
addresses = addresses.map((a, i) => (i === index ? address : a));
}
</script>
{#each addresses as address, index}
<Address value="{address}" on:change="{e => changeAddress(e.target.value, index)}" />
{/each}
<button on:click="{addAddress}">Add address</button>
<!-- Address.svelte -->
<script>
export let value = '';
</script>
<div>
<input {value} on:change />
</div>