binding angular object to model-driven form in ang

2019-02-28 06:51发布

I have created custom controls(in component class) with binding objects to form element in html, but there is an error message shown in consele that I couldnt solve, actually message makes no sense(formGroup is special key why it tries to bind it ?) here is the image that I see in developer console in chrome: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条回答
我命由我不由天
2楼-- · 2019-02-28 07:18

You need to add

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

to the module where you are using formGroup

查看更多
登录 后发表回答