可以使用nativeEloment的setFocus方法来设置焦点。
但是如何取消焦点呢?
在Angular 2+/Ionic 3应用中,如何从模板中取消输入框的选中并移除光标?
我需要取消聚焦,因为当一个输入框被选中时,移动端键盘一直处于打开状态。
编辑:该输入框是Ionic2+的ion-input。
可以使用nativeEloment的setFocus方法来设置焦点。
但是如何取消焦点呢?
在Angular 2+/Ionic 3应用中,如何从模板中取消输入框的选中并移除光标?
我需要取消聚焦,因为当一个输入框被选中时,移动端键盘一直处于打开状态。
编辑:该输入框是Ionic2+的ion-input。
1)在组件的模板中,为输入添加一个模板变量引用:
<ion-input #textInput>
2) 将 ElementRef
和 ViewChild
添加到你的组件导入中:
import { ElementRef, ViewChild } from '@angular/core'
3) 在您的组件中添加 @ViewChild
变量和相关方法:
export class AppComponent {
@ViewChild('textInput') textInput;
setFocus() {
this.textInput.nativeElement.focus();
}
removeFocus() {
this.textInput.nativeElement.blur();
}
}
您可以通过多种方式触发 setFocus()
或 removeFocus()
。以下是一个示例:
# 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();
}
}
}
对于Ionic 4用户 ;)
在尝试多种解决方案来隐藏搜索输入框键盘时,我发现了一种方法,受到了@zach-newburgh的启发。
以下方法无效:
this.keyboard.hide()
#searchInput
(keyup.enter)="searchInput.blur()"
this.searchInput.nativeElement.blur();
this.searchInput.getElementRef().nativeElement.blur();
唯一有效的解决方案
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>
希望对您有所帮助。
在 Ionic 5 上,这对我有效。
this.searchInput.getInputElement().then((input) => {
input.blur();
});
if (condition) {
this.addressLine1.nativeElement.focus();
}else{
this.addressLine1.nativeElement.blur();
}
Declare veiwChild with one public variable
@ViewChild('myActionForm', { static: false, read: ElementRef }) public actionForm: ElementRef<any>;
**add set Timeout with in the method**
setTimeout(() => {
this.actionForm.nativeElement.click();
}, 100);