gpt4 book ai didi

javascript - AngularJS2 : How to focus input like document. getElementById(..).focus 在 javascript 中?

转载 作者:行者123 更新时间:2023-11-30 11:56:52 25 4
gpt4 key购买 nike

我正在 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 {
????
}
});

最佳答案

使用 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">

不要忘记将它添加到`directives: [Focusable]

您可以像这样查询该指令

@ViewChild(Focusable) focusable:Focusable;

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

Plunker example

关于javascript - AngularJS2 : How to focus input like document. getElementById(..).focus 在 javascript 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37693091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com