我想使用#variable =" ngForm"在angular2。如何在formControl输入上使用它?每个版本的Angular都有很多变化,我不能使用#variable而不是使用" feedbackForm.controls.personalData.controls.firstName"这是如此长的磁带。不知道是否还有其他方法可以做到这一点。谢谢。
<form [formGroup]="feedbackForm" novalidate (ngSubmit)="onSubmit(this.feedbackForm)">
<div formGroupName="personalData">
<div class="form-group">
<label for="firstName">First name</label>
<input formControlName="firstName" id="firstName" type="text" class="form-control" required />
<div class="alert-info alert-danger"
*ngIf="feedbackForm.controls.personalData.controls.firstName.touched && feedbackForm.controls.personalData.controls.firstName.errors">FirstName is required</div>
</div>
...
...
...
**********构造**********
constructor(@Inject(FormBuilder) fb: FormBuilder) {
this.feedbackGroup = fb.group({
comment: ['', Validators.required]
});
this.feedbackForm = fb.group({
personalData: fb.group({
firstName: [``, Validators.required],
lastName: [``, Validators.compose([Validators.required, CustomerValidators.cannotContainSpace]), CustomerValidators.shouldBeUnique],
phoneNumber: []
}),
feedback: this.feedbackGroup
});
}
答案 0 :(得分:0)
通常,您应该不混合并匹配模型和模板驱动的表单。 我建议:
<form [formGroup]="feedbackForm" novalidate (ngSubmit)="onSubmit(this.feedbackForm)">
<div [formGroup]="personalData">
<div class="form-group">
<label for="firstName">First name</label>
<input [formControl]="firstName" id="firstName" type="text" class="form-control" required />
<div class="alert-info alert-danger"
*ngIf="firstName.touched && firstName.errors">FirstName is required</div>
</div>
在课堂内
export class thatComponent {
private firstName:FormControl;
private personalData:FormGroup;
private feedbackForm:FormGroup;
constructor(){
this.feedbackForm = .... // what ever you've done
this.personalData = this.feedbackForm.get(['personalData'])
this.firstName = this.personalData.get(['firstName'])
}
}