【发布时间】:2017-09-25 22:57:30
【问题描述】:
我正在 Angular 2 中创建一个表单。我的目标是从 API 获取数据并将其传递到表单中以进行编辑。但是,我遇到了这个错误:
异常:未捕获(承诺中):错误:./EditPatientComponent 类 EditPatientComponent 中的错误 - 内联模板:1:10 导致:formGroup 需要一个 FormGroup 实例。请传一个。
这是有错误的当前代码。
html
<section class="CreatePatient">
<form [formGroup]="patientForm" (ngSubmit)="onSubmit()">
<div class="row">
<div class="form-group col-12 col-lg-3">
<label for="firstName">First Name</label>
<input formControlName="firstName" type="text" class="form-control" id="firstName" >
</div>
<div class="row">
<div class="col-12 col-lg-2">
<button type="submit" name="submit" class="btn btn-block btn-primary">Save</button>
</div>
</div>
</form>
</section>
ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { PatientService } from './patient.service';
import { Patient } from './patient';
@Component({
templateUrl: 'editpatient.component.html'
})
export class EditPatientComponent implements OnInit {
errorMessage: string;
id: string;
editMode = true;
private patientForm: FormGroup;
private patient: Patient;
constructor(
private patientService: PatientService,
private router: Router,
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder) {
console.log("routes");
console.log(activatedRoute.snapshot.url[1].path);
}
ngOnInit() {
this.getPatient();
}
getPatient() {
this.patientService.getPatient(this.activatedRoute.snapshot.url[1].path)
.subscribe(
patient => {
this.id = this.activatedRoute.snapshot.url[1].path;
this.patient = patient;
this.initForm();
},
error => this.errorMessage = <any>error);
}
onSubmit(form){
console.log(this.patientForm);
// Post the API
};
initForm() {
let patientFirstName = '';
if (this.editMode) {
console.log(this.patient.firstName);
console.log(this.patient.lastName);
console.log(this.patient.participantUuid);
patientFirstName = this.patient.firstName;
}
this.patientForm = new FormGroup({
'firstName': new FormControl(patientFirstName)
})
};
}
任何帮助/指出我正确的方向都会很棒!谢谢!
【问题讨论】:
-
为什么 patientForm 是私有的?
-
如果你从代码中的 parientForm 中去掉 private 关键字,它的工作方式有什么不同吗?
-
它的工作方式没有任何不同。我从@Brandon 那里得到了解决方案,效果很好。