bestguy / sveltestrap

Bootstrap 4 & 5 components for Svelte
https://sveltestrap.js.org
MIT License
1.31k stars 183 forks source link

Error when setting focus to Input component #360

Closed nstuyvesant closed 3 years ago

nstuyvesant commented 3 years ago

SvelteStrap: 5.6.1 Bootstrap: 5.1.0 Svelte: 3.42.1 SvelteKit: v1.0.0-next.147

Was calling focus() when the Modal opens and it was working with a standard HTML input. When I switched it to SvelteStrap's Input component, I started getting an error:

TypeError: focusField.focus is not a function. (In 'focusField.focus()', 'focusField.focus' is undefined)

Here's the code up to that input with the HTML input (that worked) commented out:

<script lang="ts">
  import { createEventDispatcher } from 'svelte'
  import { Button, Modal, ModalBody, ModalFooter, Input } from 'sveltestrap'
  import { dialogUpsert } from '$lib/dialog'

  export let announcement: Announcement
  export let isOpen: boolean = false
  export let toggle: ()=> void
  let focusField

  const dispatch = createEventDispatcher()

  const save = async() => {
    dialogUpsert<Announcement>('announcement', announcement, toggle, dispatch)
  }

</script>

<Modal {isOpen} {toggle} on:open={() => focusField.focus()} header="Edit Announcement" body size="lg">
  <form on:submit|preventDefault={save} id="modalForm" class="needs-validation" novalidate>
    <ModalBody>
      <div class="row">
        <div class="col-6">
          <div class="form-floating mb-3">
            <Input type="datetime-local" bind:this={focusField} bind:value={announcement.expires} id="expires" placeholder="Expires" required/>
            <!-- <input type="date" bind:this={focusField} bind:value={announcement.expires} id="expires" class="form-control" placeholder="Expires" required/> -->
            <label for="expires">Expires</label>
            <div class="invalid-feedback">Expiration date required</div>
          </div>
        </div>
      </div>
bestguy commented 3 years ago

Hi, you have to bind to the Input's inner prop, Svelte won't understand bind:this with custom components:

<script>
  import { Input } from 'sveltestrap';

  let inner = undefined;

  // call inner.focus()
</script>

<Input bind:inner />
bestguy commented 3 years ago

https://sveltestrap.js.org/?path=/story/components--inputs

nstuyvesant commented 3 years ago

Oh... sorry about that and thanks for the correction!