Tương tự, không phải lúc nào chúng ta cũng biết trước loại phần tử DOM nào sẽ hiển thị. <svelte:element> sẽ giúp ích cho điều này. Giống như trong bài tập trước, chúng ta có thể thay thế một chuỗi dài các khối if bằng một phần tử động duy nhất:
App.svelte
<select bind:value={selected}>
{#each options as option}
<option value={option}>{option}</option>
{/each}
</select>
<svelte:element this={selected}>
Tôi là một <code><{selected}></code> element
</svelte:element>Giá trị this có thể là bất kỳ chuỗi nào, hoặc giá trị falsy (undefined, null, false, 0, -0, 0n, NaN) — nếu nó là falsy, không có phần tử nào được hiển thị.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
const options = ['h1', 'h2', 'h3', 'p', 'marquee'];
let selected = options[0];
</script>
<select bind:value={selected}> {#each options as option} <option value={option}>{option}</option> {/each}</select>
{#if selected === 'h1'}<h1>Tôi là một <code><h1></code> element</h1>
{:else}<p>TODO khác</p>
{/if}