Skip to content

Instantly share code, notes, and snippets.

@CK110
Forked from Manduro/keyboard-attach.directive.ts
Created December 7, 2017 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CK110/ca5f53143726fe4bbd85ea6e435e5db6 to your computer and use it in GitHub Desktop.
Save CK110/ca5f53143726fe4bbd85ea6e435e5db6 to your computer and use it in GitHub Desktop.
Ionic Keyboard Attach Directive
import { Directive, ElementRef, Input, OnDestroy, OnInit } from '@angular/core';
import { Keyboard } from '@ionic-native/keyboard';
import { Content, Platform } from 'ionic-angular';
import { Subscription } from 'rxjs/Subscription';
/**
* @name KeyboardAttachDirective
* @source https://gist.github.com/Manduro/bc121fd39f21558df2a952b39e907754
* @description
* The `keyboardAttach` directive will cause an element to float above the
* keyboard when the keyboard shows. Currently only supports the `ion-footer` element.
*
* ### Notes
* - This directive requires [Ionic Native](https://github.com/driftyco/ionic-native)
* and the [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugin-keyboard).
* - Currently only tested to work on iOS.
* - If there is an input in your footer, you will need to set
* `Keyboard.disableScroll(true)`.
*
* @usage
*
* ```html
* <ion-content #content>
* </ion-content>
*
* <ion-footer [keyboardAttach]="content">
* <ion-toolbar>
* <ion-item>
* <ion-input></ion-input>
* </ion-item>
* </ion-toolbar>
* </ion-footer>
* ```
*/
@Directive({
selector: '[keyboardAttach]'
})
export class KeyboardAttachDirective implements OnInit, OnDestroy {
@Input('keyboardAttach') content: Content;
private onShowSubscription: Subscription;
private onHideSubscription: Subscription;
constructor(
private elementRef: ElementRef,
private keyboard: Keyboard,
private platform: Platform
) {}
ngOnInit() {
if (this.platform.is('cordova') && this.platform.is('ios')) {
this.onShowSubscription = this.keyboard.onKeyboardShow().subscribe(e => this.onShow(e));
this.onHideSubscription = this.keyboard.onKeyboardHide().subscribe(() => this.onHide());
}
}
ngOnDestroy() {
if (this.onShowSubscription) {
this.onShowSubscription.unsubscribe();
}
if (this.onHideSubscription) {
this.onHideSubscription.unsubscribe();
}
}
private onShow(e) {
let keyboardHeight: number = e.keyboardHeight || (e.detail && e.detail.keyboardHeight);
this.setElementPosition(keyboardHeight);
};
private onHide() {
this.setElementPosition(0);
};
private setElementPosition(pixels: number) {
this.elementRef.nativeElement.style.paddingBottom = pixels + 'px';
this.content.resize();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment