Add tutorial for component binding (#5009)

Closes #5008

Co-authored-by: Stephane Vanraes <stephane.vanraes@fjordline.com>
Co-authored-by: pngwn <pnda007@gmail.com>
pull/6455/head
Stephane 4 years ago committed by GitHub
parent 92422fdee2
commit f9b796cabe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,5 @@
<script>
import InputField from './InputField.svelte';
</script>
<InputField />

@ -0,0 +1,9 @@
<script>
let input;
export function focus() {
input.focus();
}
</script>
<input bind:this={input} />

@ -0,0 +1,9 @@
<script>
import InputField from './InputField.svelte';
let field;
</script>
<InputField bind:this={field}/>
<button on:click={() => field.focus()}>Focus field</button>

@ -0,0 +1,9 @@
<script>
let input;
export function focus() {
input.focus();
}
</script>
<input bind:this={input} />

@ -0,0 +1,19 @@
---
title: Binding to component instances
---
Just as you can bind to DOM elements, you can bind to component instances themselves. For example, we can bind the instance of `<InputField>` to a prop named `field` in the same way we did when binding DOM Elements
```html
<InputField bind:this={field} />
```
Now we can programmatically interact with this component using `field`.
```html
<button on:click="{() => field.focus()}">
Focus field
</button>
```
> Note that we can't do `{field.focus}` since field is undefined when the button is first rendered and throws an error.
Loading…
Cancel
Save