我在Angular 2中创建了一个表单.我的目标是从API中获取数据,并将其传递到表单中进行编辑.然而,我遇到了这个错误:

例外:未捕获(promise 中):错误:错误/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)
        })
    };

}

任何帮助/给我指出正确的方向就太好了!谢谢!

推荐答案

在订阅中填充patient之前,您的patientFormundefined.因此,您试图绑定到模板解析时模板中不存在的值.

添加*ngIf以仅在Patient为真或表单组已实例化时呈现表单:

<section class="CreatePatient">
    <form *ngIf="patient" [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>

在订阅中填充患者后,patientForm实例将存在,绑定将起作用.在处理异步值时,这是一个常见的"问题".

表单并不总是有起始值,因此您还可以判断表单本身是否存在:

<form *ngIf="patientForm" [formGroup]="patientForm" (ngSubmit)="onSubmit()">

重要的一点是,表单在实例化之前不会呈现.

Angular相关问答推荐

*ngFor循环中令人困惑的Angular 行为

无法添加@angular/pwa

为什么在回调完成之前,可观察对象会返回?

茉莉花-模板中调用了如何判断角管

ANGLE DI useFactory将参数传递给工厂函数

如何在AngularJs中剪断细绳

无法在Mat-SideNav中绑定模式

如何在运行Angular应用程序的容器中访问Docker容器?

Angular AuthGuard:不推荐使用 CanActivate 和 CanActivateChild.如何更换它们?

Angular JWT Token 被添加到lazyUpdate 而不是 HttpHeaders 中的标头

Angular:为什么在我的自定义 ErrorHandler 中订阅主题不触发?

角项目更新

将 html ngModel 值传递给服务Angular

Angular 服务decorator 提供在延迟加载的根效果

react形式的formGroup.get与formGroup.controls

相对于根目录的 SCSS 导入

在Angular 4中以'yyyy-MM-dd'格式获取当前日期

此类通过 SomeModule -> SomeComponent 对消费者可见,但不会从顶级库入口点导出

如何对 *ngFor 应用数量限制?

如何使用formControlName和处理嵌套的formGroup?