Skip to content

Commit

Permalink
Add tutorial for component binding (#5009)
Browse files Browse the repository at this point in the history
Closes #5008

Co-authored-by: Stephane Vanraes <stephane.vanraes@fjordline.com>
Co-authored-by: pngwn <pnda007@gmail.com>
  • Loading branch information
3 people committed Jun 26, 2021
1 parent 92422fd commit f9b796c
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script>
import InputField from './InputField.svelte';
</script>

<InputField />
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
let input;
export function focus() {
input.focus();
}
</script>

<input bind:this={input} />
Original file line number Diff line number Diff line change
@@ -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>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
let input;
export function focus() {
input.focus();
}
</script>

<input bind:this={input} />
19 changes: 19 additions & 0 deletions site/content/tutorial/06-bindings/14-component-this/text.md
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit f9b796c

Please sign in to comment.