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+.
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();
}
}
}
For Ionic 4 users ;)
After trying multiple solution to dismiss/hide the keyboard of a search input, I found a way inspired from your solution @zach-newburgh.
Was not working :
this.keyboard.hide()
#searchInput
(keyup.enter)="searchInput.blur()"
this.searchInput.nativeElement.blur();
this.searchInput.getElementRef().nativeElement.blur();
Only working solution
this.searchInput._native.nativeElement.blur();
ts
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { TextInput } from 'ionic-angular';
...
@ViewChild('searchInput') searchInput: TextInput;
...
onSearchEnter() {
this.searchInput._native.nativeElement.blur();
}
html
<ion-input #searchInput
type="search"
(keyup.enter)="onSearchEnter()"
[(ngModel)]="searchQuery"></ion-input>
html
<ion-input #searchInput
type="search"
(keyup.enter)="searchInput._native.nativeElement.blur()"
[(ngModel)]="searchQuery"></ion-input>
Hope it will help.
Apply focus and remove Focus Based on condition:
if (condition) {
this.addressLine1.nativeElement.focus();
}else{
this.addressLine1.nativeElement.blur();
}
This worked for me on ionic 5
this.searchInput.getInputElement().then((input) => {
input.blur();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With