2017-04-23 28 views
1

我如何獲得一個HTML input元素在我的組件類的價值?如何獲取Angular 2中的HTML元素的值?

例如,我想從這個輸入元素的用戶名在我的組件類。

<div class="row"> 
    <div class="input-field col s12">     
      <input id="username" type="text" class="validate" name="username"> 
      <label for="username">Username</label> 
    </div> 
</div> 

那麼我需要的價值在我的組件類:

export class HomepageComponent { 
    username = username; 
} 
+0

https://angular.io/docs/ts/latest/guide/template-syntax.html如何使用ngModel? :) – Alex

+0

是的,我一直在研究有關ngModel,但我不能換我周圍的適當頭結合使用。 @ ajt-82 – proton

+0

我建議你看看教程。你有一個答案,是的,但如果你看看這個教程,你會得到一些基礎知識。從這裏開始:https://angular.io/docs/ts/latest/tutorial/toh-pt1.html :) – Alex

回答

3

你可以使用ngModel指令有(雙向綁定)或template變量,它會幫助你保持DOM。

<input id="username" type="text" class="validate" [(ngModel)]="userName" name="username"> 

OR

<input #usernameInput type="text" class="validate" 
    name="username" (input)="username = usernameInput.value"> 
+0

所以我這樣做早些時候,但我的問題是如何訪問組件類變量。 – proton

+0

你可以在組件類中使用'this.username'? –

+0

謝謝。這工作。 – proton