AngularJS2:如何集中输入 document.getElementById(..).focus in javascript?

AngularJS2: How to focus input like document.getElementById(..).focus in javascript?

我正在 AngularJS2 中编写一个登录表单,我希望光标在用户或密码 return 为 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 {
        ????
    }
  });

使用 中解释的指令并稍微修改一下:

@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