2017-09-19 25 views
0

我有一個按鈕和另一個div與一些內容。我想在用戶點擊按鈕時將焦點設置到div。我知道在JavaScript中我可以通過document.getElementById(「divID」)。focus();但是在打字稿中有任何方法。如何使用Angular with TypeScript對點擊按鈕聚焦一個div塊

+1

這個問題的前提是錯誤的。 TypeScript方式是根據定義的JavaScript方式。 –

+1

@AluanHaddad前提已改變。他使用角標籤顯然是爲了角度。 – alexKhymenko

回答

0

可以在HTML

<button (click)='focus()'> focus</button> 

使用@ViewChild

@ViewChild('selector') selector: ELementRef; 

focus() { 
    this.selector.nativeElement.focus() 
} 

和2的方法將是

<sole-element #el> <sole-element> 
<button (click)='focus(el)'> focus</button> 
or 
<button (click)='el.focus()'> focus</button> 

和TS文件

focus(el) { 
    el.nativeElement.focus() 
} 
+0

這個問題的前提是錯誤的。 TypeScript方式是根據定義的JavaScript方式。因此,這個答案不適用於問如何在TypeScript中做到這一點,而不是如何在Angular中做到這一點 –

0

試試這個:

在HTML文件:

<div> 
    <button class="btn btn-primay" (click)="onFocus()">onFocus</button> 
</div> 
<div> 
     <input type="text" name="name" #focusContent> 
</div> 

component.ts

import { Component, ElementRef, ViewChild } from '@angular/core'; 

export class AppComponent { 
    @ViewChild('focusContent') el: any; 

    onFocus() { 
     this.el.nativeElement.focus(); 
    } 
}