如何在角度2中获取表单值

How get form vlaues in 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);
 }
}

您需要 name 表单中的属性,以及与 ngModel 的绑定,这些 Angular 可以跟踪输入元素并将其与表单控件相关联。

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

没有这些,您的表单对象将只是一个空对象。

DEMO

你应该这样做

<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);
}