angularjs2 formGroup和formControlName

时间:2017-07-31 10:55:55

标签: html node.js typescript angular2-forms

我是这个angularjs2的新手,我刚刚创建了一个注册 页面使用formGroup formControlName页面并获得将null值传递给对象的错误。

HTML代码

<div class="col-md-8 col-md-offset-2">
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
            <label for="firstName">firstname</label>
            <input 
                    type="text" 
                    id="firstName" 
                    class="form-control"
                    formControlName="firstName">
        </div>
        <div class="form-group">
            <label for="lastName">lastName</label>
            <input 
                    type="text" 
                    id="lastName" 
                    class="form-control"
                    formControlName="lastName">
        </div>
        <div class="form-group">
            <label for="email">Mail</label>
            <input 
                    type="email" 
                    id="email" 
                    class="form-control"
                    formControlName="email">
        </div>
        <div class="form-group">
            <label for="password">password</label>
            <input 
                    type="password" 
                    id="password" 
                    class="form-control"
                    formControlName="password">
        </div>
        <button 
            class="btn btn-primary" 
            type="submit"
            [disabled]="!myForm.valid">Submit</button>
    </form>
</div>


<!--
    [formGroup]="myForm" is used to instruct the angular2 to don't use ur own form use mine.'

    formControlName is used to identify which attribute to match in SignupComponent class 
    -->

signup.component.ts文件

 import { Component, OnInit} from '@angular/core';
    import { FormGroup, FormControl, Validators} from '@angular/forms';

    import { AuthService} from './auth.service';
    import { User} from './user.model';

    @Component({
        selector:'app-signup',
        templateUrl: './signup.component.html'
    })
    export class SignupComponent implements OnInit{
        myForm: FormGroup;

        constructor(private authService : AuthService) {}

        onSubmit(){

                  console.log(this.myForm);

            this.myForm.reset();
        }

        ngOnInit(){
            this.myForm = new FormGroup({
                firstName: new FormControl(null, Validators.required),
                lastName: new FormControl(null, Validators.required),
                email: new FormControl(null, [
                    Validators.required,
                    Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}")
                ]),
                password: new FormControl(null, Validators.required),

            });
        }
    }

我将值传递给对象时会出现此错误 将空值传递给对象

时出错

enter image description here

1 个答案:

答案 0 :(得分:0)

请将表单对象的引用解析为onSubmit()

相关问题