聚焦< input>元素 [英] Focus an <input> element

查看:67
本文介绍了聚焦< input>元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在div中有很多input框,我需要以编程方式集中其中的一个.

I've many input boxes in a div and I need to focus one of them programmatically.

该怎么做?

类似于:

<div>
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="text" name="txt3" />
<input type="text" name="txt4" />
<input type="text" name="txt5" />
<input type="text" name="txt6" />
</div>
<button (click)="selectSample()" />

selectSample() {
    ?????????('txt3').focus();
    console.log('Button pressed, txt3 has been selected');
}

推荐答案

@Component({
  selector: 'my-app',
  template: `
<div>
<input #input type="text" name="txt1" />
<input #input type="text" name="txt2" />
<input #input type="text" name="txt3" />
<input #input type="text" name="txt4" />
<input #input type="text" name="txt5" />
<input #input type="text" name="txt6" />
</div>
<button (click)="selectSample()">click</button>
`
})
export class App {
  @ViewChildren('input') inputs;

  selectSample() {
    // console.debug(this.inputs.toArray().find((e) => {
    //  return e.nativeElement.getAttribute('name') == 'txt3';
    //}).nativeElement.value);

    this.inputs.toArray().find((e) => {
      return e.nativeElement.getAttribute('name') == 'txt3';
    }).nativeElement.focus();

  }
}

柱塞示例

这篇关于聚焦&lt; input&gt;元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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