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

Nat*_*ael 4 mobile focus input ionic2 angular

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

但是移除焦点呢?

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

我需要移开焦点,因为当输入获得焦点时,移动键盘会保持打开状态。

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

Zac*_*rgh 5

1)在您组件模板的输入中添加一个模板变量引用:

<ion-input #textInput>
Run Code Online (Sandbox Code Playgroud)

2)在组件的导入中添加ElementRefViewChild

import { ElementRef, ViewChild } from '@angular/core'
Run Code Online (Sandbox Code Playgroud)

3)@ViewChild在您的组件中添加变量和相关方法:

export class AppComponent {

  @ViewChild('textInput') textInput;

  setFocus() {
    this.textInput.nativeElement.focus();
  }

  removeFocus() {
    this.textInput.nativeElement.blur();
  }

}
Run Code Online (Sandbox Code Playgroud)

您可以触发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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)