When adding clearInput=“true” to ion-input, a clear icon appears and clicking to it clears the input
… but input looses the focus (and, on android device, soft keyboard gets also hidden).
How can I keep the focus in the input (and the keyboard displayed) so that when clicking on clear icon, user can start typing the new input value straight, without the need to (re)select it again?
//when i try to focus
const prompt = this.alertCtrl.create({
title: ‘Nota’,
message: "Su nota es: " + total,
buttons: [
{
text: 'OK',
handler: data => {
// here i try to focus when the user click in ok
this.puntajeObtenido.setFocus();
}
}
]
});
prompt.present();
// i focus the input when the alert end
this.puntajeObtenido.setFocus();
same problem, the input focus and then 1 sec later the keyboard hide and lose the focus
sorry about my english
I have the same problem. When I hit clearInput it’s because I want to enter something else in the inputbox but it loses focus after the input box is cleared and the user has to tap it again.
First we need to create a little helper function to prevent default events and event propagation:
/**
* @private
* @function stopInputBubble
* @description Helper function to stop default events and event propagation
* @param {any} evt The event, which was initially triggered and should be prevented
* @return {void}
*/
private stopInputBubble(evt: any) {
evt.preventDefault();
evt.stopPropagation();
return;
}
Now we need to create the function itself, which prevents closing the Keyboard on hitting the clear button within the <ion-input>:
/**
* @protected
* @function clearInput
* @description Helper function to prevent closing the keyboard on hitting the clear button
* @return {void}
*/
protected clearInput(): void {
// Create a variable, storing the native button element, alternatively use a `@ViewChild`
const elem: HTMLElement = document.querySelector('button.text-input-clear-icon.button-clear');
// Programatically add multiple event listeners
['click', 'mousedown', 'touchdown', 'touchmove', 'touchstart'].forEach((evt: any) => {
elem.addEventListener(evt, this.helperCtrl.stopInputBubble, false);
return;
});
// Add event listener for `touchend`, triggered by a mobile device
elem.addEventListener('touchend', (evt: any) => {
this.stopInputBubble(evt);
this.myInputNgModel = '';
return;
});
// Add event listener for `mouseup`, triggered by a browser
elem.addEventListener('mouseup', (evt: any) => {
this.stopInputBubble(evt);
this.myInputNgModel = '';
return;
});
return;
}
Don’t forget to call this.clearInput() whilst initializing your module, for example in IonViewDidLoad or something like this.
I hope it helps someone, whether it’s a little bit hacky or not .