我已经在angular2中创建了模型驱动的表单,我在html模板中创建了具有相同名称指令的对象,但不知怎的,如下图所示会出现错误:
postmessage.component.ts:
import { Component } from '@angular/core';
import {FormControl,FormGroup,FormBuilder,Validators} from '@angular/forms';
@Component({
moduleId:module.id,
selector: 'post-message',
templateUrl: '../../templates/postmessage.component.html'
})
export class PostComponent {
form = new FormGroup({
username:new FormControl('',Validators.required),
email:new FormControl('',Validators.required)
})
signup(){
console.log(this.form.value);
}
}
postmessage.component.html:
<form class="from-horizontal" [formGroup]="form" (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" formControlName="username">
<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" formControlName="email">
</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>
如何解决?
答案 0 :(得分:2)
form = new FormControl({
应该是
form = new FormGroup({