设置焦点在IOS支持设备上不起作用 [英] Set focus doesn't work on IOS supporting devices

查看:81
本文介绍了设置焦点在IOS支持设备上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,以编程方式在<input>上设置焦点在IOS支持的设备上不起作用.它在其他任何地方都按预期工作.我正在使用本地模板变量. 这是一个片段,应该将焦点设置为单击按钮时的输入:

In my code, setting focus, programatically, on an <input>, doesn't work on IOS supporting devices. It works as expected everywhere else. I am using local template variable. Here is a snippet which is supposed to set the focus to the input on the button click:

HTML

<button type="button" (click)="input.focus()">Click to show and set focus</button>
<input #input type="text" >

演示

DEMO

推荐答案

您可以使用以下内容:

@Component({
  selector: 'my-app',
  template: `
    <div *ngFor="let item of [1,2,3,4]; let i = index">
      <button type="button" (click)="display(i)">Click to show and set focus</button>
      <input #theInput *ngIf="show === i" type="text" >
    </div>
  `,
})
export class App {
  show = -1; 

  @ViewChild('theInput')
  private theInput;

  constructor() {
  }

  display(i) {
    this.show = i;
    setTimeout(() => this.theInput.nativeElement.focus(), 0);
  }
}

我不确定是否有比setTimeout更好的用法,但是由于仅在由show的更改触发更改检测之后才将输入添加到DOM,所以未定义theInput (或之前显示的输入).

I'm not sure if there is something more elegant than the usage of setTimeout, but since the input is only added to the DOM after the change detection which is triggered by the change of show, theInput is undefined (or the previously shown input) at that time.

演示: http://plnkr.co/edit/A0ZO0hyuR61nUdiSvzFj?p=preview

事实证明,还有一些更优雅的方法:AfterViewChecked:

It turns out there is something more elegant: AfterViewChecked:

export class App {
  show = -1; 
  shouldFocus = false;

  @ViewChild('theInput')
  private theInput;

  constructor() {
  }

  display(i) {
    this.show = i;
    this.shouldFocus = true;
  }

  ngAfterViewChecked() {
    if (this.shouldFocus) {
      this.theInput.nativeElement.focus();
      this.shouldFocus = false;
    }
  }
}

请参阅更新的演示: http://plnkr.co/edit/lXTRDGLKwkAAukEQGQjq?p=预览

这篇关于设置焦点在IOS支持设备上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆