无法访问提交的表单数据

时间:2016-10-19 11:42:24

标签: forms angular

我从angular2开始。我有一个简单的模板驱动表单,我可以在控制台中访问数据。但我传递数据有问题。这是我的代码。

import {Component} from "angular2/core";

@Component({
selector: 'my-template-driven',
template:`
    <h2>Sign-up form</h2>
    <form (ngSubmit)="onSubmit(f)" #f="ngForm">
        <div>
            <label for="email">Mail</label>
            <input ngControl="email" type="text" id="email" required #email="ngForm">
            <span class="validation-error" *ngIf="!email.valid">Not Valid</span>
        </div>
          <div>
            <label for="password">Password</label>
            <input ngControl="password" type="text" id="password" required #password="ngForm">
            <span class="validation-error" *ngIf="!password.valid">Not Valid</span>
        </div>
          <div>
            <label for="confirm-password">Confirm Password</label>
            <input ngControl="confirm-password" type="text" id="confirm-password" required #passwordConfirm="ngForm">
            <span class="validation-error" *ngIf="!passwordConfirm.valid">Not Valid</span>
        </div>
        <button type="submit" [disabled]="!f.valid || password.value !== passwordConfirm.value">Submit</button>
    </form>
    <h2>You Submitted</h2>


`
})
export class TemplateDrivenFormComponent {
user: {email: '', password: ''};

onSubmit(form){
    //console.log(form);
    this.user.email = form.value['email'];
    //this.user.password = form.controls['password'].value;
}

}

我经常收到此angular2.js:23941 ORIGINAL EXCEPTION: TypeError: Cannot set property 'email' of undefined错误。如何访问提交表单的数据。

2 个答案:

答案 0 :(得分:1)

您没有正确声明您的本地,并且您必须在声明它时初始化它,或者在您的构造函数中初始化它

user: any;

constructor() {
    this.user = {email: "", password: ""} as any;
}

:后,您必须提供类型。

答案 1 :(得分:0)

HTML输入中必须具有“ ngModel”属性。