2016-06-08 144 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