如何在 Angular 2+/Ionic2+ 中取消 ion-input 的焦点

5

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

但是如何取消焦点呢?

在Angular 2+/Ionic 3应用中,如何从模板中取消输入框的选中并移除光标?

我需要取消聚焦,因为当一个输入框被选中时,移动端键盘一直处于打开状态。

编辑:该输入框是Ionic2+的ion-input。


如何使用blur()函数? - kit
我忘了说它是一个ion-input。因此,它的原生元素中没有blur()和focus()。 - Natanael
5个回答

9

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

我忘了说它是一个ion-input。因此,它的原生元素中没有blur()和focus()。 - Natanael
根据文档,它应该可以工作:this.textInput的返回值是什么?但问题与(mouseover)(mouseout)有关。我将从示例中删除它们! - Zach Newburgh

3

对于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

在 Ionic 5 上,这对我有效。

this.searchInput.getInputElement().then((input) => {
  input.blur();
});

谢谢James D.你的方法有效并帮助我解决了Ionic 5中的失焦问题。 - LHLK

1
应用焦点并根据条件移除焦点:

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

正如问题中提到的,“它是一个ion-input。因此,它的本地元素中没有blur()和focus()。”这个答案不会有帮助。 - Hirumina

0
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);

1
请勿仅粘贴没有支持信息的代码块。如何回答问题 - CascadiaJS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接