matt93
matt93

Reputation: 123

How to display the keyboard automatically on page load

I'm building a mobile application with NativeScript-Vue. I have a TextField on the page, and want the keyboard to automatically display when the page/screen loads, rather than having to tap on the TextField.

I have assigned my TextField a ref of 'textFieldId' and have written a function which is supposed to target this TextField and bring it into focus. I've put this function in the methods section of the component, and call it within the mounted() hook.

The keyboard doesn't show on page load, and I'm unsure whether it needs to be in a different hook? I've done a console log of the TextField which I'm targeting, and it's definitely targeted it. I also set the function to run on the tap event of another element on the page, and the keyboard displays as expected.

I am running the application in an Android emulator, but have also checked on my iPhone with the command tns preview, and the issue is still the same - so I don't believe this is a device-specific issue.

<script>
    export default {
        mounted() {
            console.log('mounted')
            showKeyboard()
        },
        methods: {
            showKeyboard () {
                this.$refs.textFieldId.nativeView.focus()
        }
    }
</script>

And the TextField

<TextField
    hint="Type here"
    class="input type-text"
    ref="textFieldId"/>

The keyboard doesn't display on page load - it only displays when I click on the TextField. I would like it to display automatically without any user input.

Upvotes: 4

Views: 1957

Answers (1)

TomG
TomG

Reputation: 538

Answered here. Anyways, that's what I did on NativeScript-Vue:

<template>
    <TextField @loaded="showKeyboard" />
</template>

<script>
import * as utils from "tns-core-modules/utils/utils";

export default {
    methods: {
        showKeyboard({ object }) {
            if (object.android) {
                setTimeout(() => {
                    object.focus();
                    utils.ad.showSoftInput(object);
                }, 10);
            } else {
                object.focus();
            }
        }
    }
}
</script>

Upvotes: 2

Related Questions