Part 3 / Special elements / <svelte:component>
A component can change its category altogether with <svelte:component>
. Instead of a sequence of if
blocks...
{#if selected.color === 'red'}
<RedThing/>
{:else if selected.color === 'green'}
<GreenThing/>
{:else if selected.color === 'blue'}
<BlueThing/>
{/if}
...we can have a single dynamic component:
<svelte:component this={selected.component}/>
The this
value can be any component constructor, or a falsy value — if it's falsy, no component is rendered.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
import RedThing from './RedThing.svelte';
import GreenThing from './GreenThing.svelte';
import BlueThing from './BlueThing.svelte';
const options = [
{ color: 'red', component: RedThing },
{ color: 'green', component: GreenThing },
{ color: 'blue', component: BlueThing }
];
let selected = options[0];
</script>
<select bind:value={selected}>
{#each options as option}
<option value={option}>{option.color}</option>
{/each}
</select>
{#if selected.color === 'red'}
<RedThing />
{:else if selected.color === 'green'}
<GreenThing />
{:else if selected.color === 'blue'}
<BlueThing />
{/if}
initialising