How to remove focus from a ion-input in Angular 2+/Ionic2+
angular, focus, input, ionic2, mobile
Solution
1) Add a template variable reference to your input in your component's template:
<ion-input #textInput>
2) Add `ElementRef` and `ViewChild` to your component's imports:
import { ElementRef, ViewChild } from '@angular/core'
3) Add `@ViewChild` variable and relevant methods to your component:
export class AppComponent {
@ViewChild('textInput') textInput;
setFocus() {
this.textInput.nativeElement.focus();
}
removeFocus() {
this.textInput.nativeElement.blur();
}
}
You can trigger `setFocus()` or `removeFocus()` in a number of ways. Here's an example:
# app.component.html
<ion-input #textInput>
# app.component.ts
import { HostListener } from '@angular/core';
export class AppComponent {
[previous code elided for readability]
isInputActive: boolean;
@HostListener('document:click', ['$event'])
handleClickEvent(event: MouseEvent): void {
if (document.activeElement !== this.textInput.nativeElement) {
this.textInput.nativeElement.blur();
}
}
}
Problem
It is possible to set focus using setFocus method from nativeEloment. But how about remove focus? How could I remove the cursor from and unselect an input from a template in a Angular 2+/Ionic 3 app? I need to remove the focus because the mobile keyboard keeps open while a input has focus. Edit: The input is a ion-input of Ionic2+.