Skip to content

Instantly share code, notes, and snippets.

@somq
Created August 16, 2020 22:21
Show Gist options
  • Save somq/7dcfca8dbaaa77a80130b7d4d0e4688f to your computer and use it in GitHub Desktop.
Save somq/7dcfca8dbaaa77a80130b7d4d0e4688f to your computer and use it in GitHub Desktop.
Ionic 5 Keyboard Attach Service
import { Injectable, OnDestroy } from '@angular/core';
import { Plugins } from '@capacitor/core';
import { Platform } from '@ionic/angular';
import { fromEvent, Subscription } from 'rxjs';
const { Keyboard } = Plugins;
/**
* @originalsource https://gist.github.com/Manduro/bc121fd39f21558df2a952b39e907754
*
* Usage
export class MyServcieOrComponent {
private result: ManualItemCreateAlertInputs;
constructor(
private KbAttach: KeyboardAttachService
private alertController: AlertController
) { }
async showAlert() {
// Present the alert
const manualItemCreateAlert = await this.alertController.create(alertDefaults);
// @note quickfix for kb over the input
// @see https://github.com/ionic-team/ionic-framework/issues/21924
this.KbAttach.init(manualItemCreateAlert)
await manualItemCreateAlert.present();
}
}
*/
@Injectable({
providedIn: 'root'
})
export class KeyboardAttachService implements OnDestroy {
private onShowSubscription: Subscription;
private onHideSubscription: Subscription;
element: HTMLIonAlertElement;
constructor(
private platform: Platform,
) {
if (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();
}
}
init(element: HTMLIonAlertElement) {
this.element = element
}
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) {
if (this.element !== undefined) {
this.element.style.marginBottom = pixels + 'px';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment