角度2:formGroup需要一个FormGroup实例.请传递一个 [英] Angular 2: formGroup expects a FormGroup instance. Please pass one in

查看:135
本文介绍了角度2:formGroup需要一个FormGroup实例.请传递一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a form in Angular 2. My goal is to get data from the API and pass it into the form for editing purposes. However, I am running into this error:

例外:未捕获(承诺):错误:./EditPatientComponent类EditPatientComponent中的错误-内联模板:1:10,原因是:formGroup需要FormGroup实例.请传递一个.

EXCEPTION: Uncaught (in promise): Error: Error in ./EditPatientComponent class EditPatientComponent - inline template:1:10 caused by: formGroup expects a FormGroup instance. Please pass one in.

这是当前有错误的代码.

Here is the current code with the error.

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)
        })
    };

}

任何帮助/向正确的方向指点都会很棒!谢谢!

Any help/pointing me in the right direction would be great! Thanks!

推荐答案

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

Your patientForm is undefined until the patient in the subscription is populated. As such, you're trying to bind to a value that doesn't exist in the template at the time the template is parsed.

添加*ngIf仅在患者是真实的或实例化表单组时才呈现表单:

Add an *ngIf to render the form only when patient is truthy, or the form group is instantiated:

<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实例,并且绑定将起作用.在处理异步值时,这是常见的陷阱".

When the patient is populated in the subscription, the patientForm instance will exist and the binding will work. It's a common "gotcha" when dealing with async values.

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

Forms don't always have starting values, so you can also check for the existence of the form itself:

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

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

The important part is that the form isn't rendered until its instantiated.

这篇关于角度2:formGroup需要一个FormGroup实例.请传递一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆