Skip to content

Instantly share code, notes, and snippets.

@Youness-e
Forked from Manduro/keyboard-attach.directive.ts
Last active December 24, 2019 10:02
Show Gist options
  • Save Youness-e/5c4f49f3aaa4ee90f45b75818764114d to your computer and use it in GitHub Desktop.
Save Youness-e/5c4f49f3aaa4ee90f45b75818764114d 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/ngx';
import { Platform } from '@ionic/angular';
import { fromEvent, Subscription } from 'rxjs';
/**
* @source https://gist.github.com/Youness-e/5c4f49f3aaa4ee90f45b75818764114d
* @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/ionic-team/ionic-native )
* and the [Ionic Keyboard Plugin](https://github.com/ionic-team/cordova-plugin-ionic-keyboard).
* - Currently tested to on iOS and Android
* - 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: any;
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.platform.is('android')) {
this.onShowSubscription = fromEvent(window, 'keyboardWillShow').subscribe((e) => { this.onShow(e); });
this.onHideSubscription = fromEvent(window, 'keyboardWillHide').subscribe((e) => { this.onHide(); });
}
}
ngOnDestroy() {
if (this.onShowSubscription) {
this.onShowSubscription.unsubscribe();
}
if (this.onHideSubscription) {
this.onHideSubscription.unsubscribe();
}
}
private onShow(e) {
const 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.marginBottom = pixels + 'px';
this.content.scrollToBottom();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment