2017-05-29 42 views
2

如何從窗體獲取值。我曾嘗試下面的代碼:如何在angular2中獲取窗體

import {Component} from "@angular/core"; 
import {AuthService} from "./AuthService"; 


interface Credentials { 
    username: string, 
    password: string 
} 

@Component({ 
    selector: 'login', 
    template: ` 
    <form #f="ngForm" (ngSubmit)="onLogin(f.value)" *ngIf="!auth.loggedIn()"> 
    <input type="text" placeholder="username" ngControl="username"> 
    <input type="password" placeholder="password" ngControl="password"> 
    <button type="submit">Submit</button>  
    </form> 
` 
}) 

export class LoginComponent { 

credentials: Credentials; 

constructor(private auth: AuthService) {} 

onLogin(credentials) { 

console.log("username"+credentials.username,"password"+credentials.password); 
this.auth.login(credentials); 
} 
} 
+0

您是否收到任何錯誤? –

回答

3

您需要name屬性在您的形式,以及與ngModel結合,與這些角度可以跟蹤輸入的元素並將其與formcontrol關聯。

<input type="text" placeholder="username" name="username" ngModel> 
<input type="password" placeholder="password" name="password" ngModel> 

沒有這些,你的表單對象將只是一個空對象。

DEMO

+0

謝謝。可能我錯誤的ngControl指令undestand。 –

3

你應該做這樣的

<form #f="ngForm" (ngSubmit)="onLogin(f.value)"> 
    <input type="text" placeholder="username" name="username" ngModel> 
    <input type="password" placeholder="password" name="password" ngModel> 
    <button type="submit">Submit</button>  
</form> 

而且

onLogin(f){ 
    console.log("username :"+f.username,"password :"+f.password); 
} 
相關問題