AngularJS2:如何将注意力集中在document.getElementById(..)。焦点在javascript中?

时间:2016-06-08 04:12:08

标签: javascript angularjs angular focus

我正在AngularJS2中编写一个登录表单,当用户或密码返回false时,我希望游标聚焦用户名输入。我该怎么办?

<input type="text" class="form-control" #inputUsername placeholder="Username" autofocus ngControl="username" [(ngModel)]="username">
<input type="password" class="form-control" #inputPassword placeholder="Password" ngControl="password" [(ngModel)]="password">

this.loginService.getAuth(username, password)
  .subscribe(auth => {
    if (auth == true) {
        ????
    } else {
        ????
    }
  });

1 个答案:

答案 0 :(得分:3)

使用https://stackoverflow.com/a/34573219/217408中说明的指令并对其进行修改:

@Directive({
  selector : '[focusable]'
})
class Focusable {
  constructor(public renderer: Renderer, public elementRef: ElementRef) {}

  focus() {
    this.renderer.invokeElementMethod(
      this.elementRef.nativeElement, 'focus', []);
  }
}

然后像

一样使用它
<input focusable type="text" class="form-control" #inputUsername placeholder="Username" autofocus ngControl="username" [(ngModel)]="username">
<input type="password" class="form-control" #inputPassword placeholder="Password" ngControl="password" [(ngModel)]="password">

别忘了将它添加到`指令:[Focusable]

您可以查询该指令,例如

@ViewChild(Focusable) focusable:Focusable;

...
if(auth == true) {
  ...
} else {
  this.focusable.focus();
}

Plunker example