将角度对象绑定到angular2中的模型驱动形式

时间:2016-11-23 12:05:21

标签: angular angular2-forms

我创建了自定义控件(在组件类中),带有绑定对象以在html中形成元素,但是在consele中显示的错误消息我无法解决,实际上消息没有意义(formGroup是特殊键,为什么它尝试绑定吗?)这是我在开发人员控制台中看到的图像:enter image description here

form.component.html:

<div class="row">
    <form class="from-horizontal" [formGroup]="form" formControlName="username" formControlName="email" (ngSubmit)="signup()">
        <div class="form-group row">
            <label for="username" class="control-label col-md-2">Name:</label>
            <div class="col-md-6">
                <input type="text" id="username"  class="form-control" >
                <div class="alert alert-danger"
                *ngIf="!form.controls['username'].valid"
                >
                    User name is required.
                </div>
            </div>
        </div>
        <div class="form-group row">
            <label for="email" class="control-label col-md-2">Email:</label>
            <div class="col-md-6">
                <input type="email" id="email" class="form-control" >
            </div>
            <div class="alert alert-danger"
            *ngIf="!from.controls['email'].valid"
            ></div>
        </div>
        <div class="form-group row">
            <label for="" class="control-label col-md-2"></label>
            <div class="col-md-6">
                <input type="submit" class="btn btn-primary">
            </div>
            </div>
    </form>
</div>

form.component.ts

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

@Component({
    moduleId:module.id,
    selector: 'post-message',
    templateUrl: '../../templates/postmessage.component.html'
})
export class PostComponent {
    form = new FormControl({
        username:new FormControl('',Validators.required),
        email:new FormControl('',Validators.required)
    })
    signup(){
        console.log(this.form.value);
    }
 }

1 个答案:

答案 0 :(得分:1)

您需要添加

 @NgModule({
   imports: [BrowserModule, FormsModule, ReactiveFormsModule], // <<<===
   ...
 })

到您正在使用的模块formGroup

相关问题