2017-05-29 9 views
2

フォームから値を取得する方法。これらの角度は、入力要素を追跡し、formcontrolに関連付けることができてあなたは、自分のフォームでname属性に必要なだけでなく、ngModelとの結合どのように角度2のフォームを取得

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

:私は、次のコードを試してみました。

<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); 
} 
関連する問題