Focus an <input> element

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

  }
}

Plunker example


Take a look at the ViewChild (and ViewChildren like Gunter suggests) annotations.

You can do something like this:

@Component({
  selector: 'samples',
  template: `
    <div>
      <input type="text" name="txt1">
      <input type="text" name="txt2">
      <input type="text" name="txt3" #input3>
      <input type="text" name="txt4">
      <input type="text" name="txt5">
      <input type="text" name="txt6">
    </div>
    <button (click)="selectSample()">select</button>`
})    
export class SamplesComponent {

  @ViewChild('input3') input3:ElementRef;

  constructor(private _renderer : Renderer) {}

  public selectSample() {
     //as per Eric's suggestion
     this._renderer.invokeElementMethod(this.input3.nativeElement, 'focus', []);
  }
}

Tags:

Angular