Angular 2 - 从DOM中选择对象并设置焦点

Mar*_* Jr 9 angular

我可以在文档或谷歌示例中找到这样的东西.

我在div中有很多输入框,我需要以编程方式选择一个.怎么做 ?

就像是

<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');
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 11

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

  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker的例子


Pie*_*Duc 8

看看ViewChild(和ViewChildrenGunter建议的那样)注释.

你可以这样做:

@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', []);
  }
}
Run Code Online (Sandbox Code Playgroud)