2017-05-29 61 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); 
} 
相关问题