离子:自动聚焦文本字段

问题描述

我知道这个问题已被问过很多次,但我找不到我的解决方案:

我正在尝试在页面加载时自动聚焦文本字段,如下所示:

HTML:

<input type="text" #autofocusfield>

TS 文件

相关导入

import { Component,ViewChild } from '@angular/core';

自动对焦代码

export class Tab1Page {
  @ViewChild('autofocusfield') inputtext; 

ionViewDidLoad() {         
    setTimeout(() => {
      this.inputtext.setFocus();
    },500);
  }

我也尝试使用 autofocus='true' 但没有用,有人可以指导我如何实现这一点

解决方法

这就是您所需要的一切。此stackblitz link

中的演示
@ViewChild("autoFocus") private af: ElementRef;
constructor(public navCtrl: NavController) {}
ngAfterViewChecked() {
  this.af.nativeElement.focus();
}

你只需要在 ngAfterViewChecked() 钩子中设置 focus() 方法。

HTML 模板是..

<input #autoFocus type="text" >