如何将焦点设置在适用于 IOS 支持设备的输入上?

How to set focus on an input that works on IOS supporting devices?

我的目标是通过按钮单击方法将焦点设置在输入上。

我使用了模板变量,但通过组件代码执行它似乎给出了相同的结果。

这在我测试的所有设备(MacBook 和一些移动设备)上都按预期工作,无论浏览器是什么,即 Safari、Chrome、Firefox,但是它在 iOS 上不起作用配套设备。没有任何反应。
这是代码片段,应该将焦点设置为单击按钮时的输入。

重要提示:在 iPhone 或 iPad 上应该是 运行。

HTML

<input #input type="text">

<button type="button" (click)="input.focus()">Click to set focus on the input</button>

这里是一个小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 的用法更优雅的东西,但由于输入仅在由 [=12 的变化触发的变化检测之后添加到 DOM =], theInput 当时未定义(或先前显示的输入)。

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

编辑:

原来还有更优雅的东西: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=preview