如何从Angular 2 + / Ionic2 +中的离子输入中移除焦点

时间:2017-05-02 20:23:02

标签: angular mobile input ionic2 focus

可以使用nativeEloment中的setFocus方法设置焦点。

但是如何移除焦点?

如何从Angular 2 + / Ionic 3应用程序中删除光标并取消选择模板中的输入?

我需要移除焦点,因为移动键盘在输入有焦点时保持打开状态。

编辑:输入是Ionic2 +的离子输入。

4 个答案:

答案 0 :(得分:4)

1)在组件模板中为输入添加模板变量引用:

<ion-input #textInput>

2)将ElementRefViewChild添加到组件的导入中:

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();
    }
  }
}

答案 1 :(得分:2)

适用于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方式

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和最快的方式

html

<ion-input #searchInput
           type="search"
           (keyup.enter)="searchInput._native.nativeElement.blur()"
           [(ngModel)]="searchQuery"></ion-input>

希望这会有所帮助。

答案 2 :(得分:0)

根据条件应用焦点和移除焦点:

if (condition) {
  this.addressLine1.nativeElement.focus();
}else{
  this.addressLine1.nativeElement.blur();
}

答案 3 :(得分:0)

这在 ionic 5 上对我有用

this.searchInput.getInputElement().then((input) => {
  input.blur();
});
相关问题