2016-06-08 69 views
1

我正在AngularJS2中编写登录表单,并且我希望光标在用户或密码返回false时将用户名输入重点关注。我该怎么做?AngularJS2:如何将焦点输入像document.getElementById(..)。焦点在JavaScript中?

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

回答

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

不要忘了将它添加到`指令:[可聚焦]

您可以查询该指令像

@ViewChild(Focusable) focusable:Focusable; 

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

Plunker example

+0

我得到一个错误“无法读取属性‘专注’的未定义”。 这封信'this.focusable.focus();'是错误 – Matiratano

+0

您是否在构造函数中调用'this.focusable.focus()'?在调用ngAfterViewInit()之前,不会设置@ViewChild()查询。我添加了一个Plunker示例。 –

+0

我明白了。是工作!!!非常感谢你。 – Matiratano