user3844198
user3844198

Reputation: 205

Ionic2 - Keyboard Open/Close State Detection

I'm looking for a simple solution to detect whether keyboard on mobile device has been opened / closed (stack: Ionic2, Angular2).

Does Ionic propagate any 'keyboard-open' or 'keyboard-close' class out into the body/html?

Upvotes: 2

Views: 3592

Answers (4)

Josh O'Connor
Josh O'Connor

Reputation: 4962

Try this plugin: https://ionicframework.com/docs/native/keyboard/

window.addEventListener('keyboardWillShow', (event) => {
    // Describe your logic which will be run each time when keyboard is about to be shown.
    console.log(event.keyboardHeight);
});

Upvotes: 0

mohsen solhnia
mohsen solhnia

Reputation: 376

ugly answer but works like charm:

import {NgZone} from '@angular/core';
public IsKeyboardOpen:boolean=false;
    constructor(public ngZ:NgZone)
    {
        var innerHeight=window.innerHeight;
        window.onresize = (e) =>
       {
        this.ngZ.run(() => 
        {
          if(window.innerHeight< innerHeight)
          {
            this.IsKeyboardOpen=true;
          }
          else
          {
            this.IsKeyboardOpen=false;
          }
        });
    };
    }

Upvotes: 0

AishApp
AishApp

Reputation: 4162

Keyboard is native to mobile device.So you need native plugins to check its functionalities. Install the cordova plugin and ionic native typings as below

ionic plugin add ionic-plugin-keyboard
npm install --save @ionic-native/keyboard

Add the below lines of code to check the keyboard open and close

import { Keyboard } from '@ionic-native/keyboard';

constructor(private keyboard: Keyboard) {

...
//Observes when the keyboard is shown
this.keyboard.onKeyboardShow(); 

   //Observes when the keyboard is hidden
   this.keyboard.onKeyboardHide();

}

Upvotes: 4

Pedro Castilho
Pedro Castilho

Reputation: 10532

Ionic does not emit keyboard-open or keyboard-close, but there is ionic-plugin-keyboard which does just that. It will fire native.keyboardshow and native.keyboardhide events. You can also query the Keyboard.isVisible property.

Upvotes: 1

Related Questions