【问题标题】:Angular 2: formGroup expects a FormGroup instance. Please pass one inAngular 2:formGroup 需要一个 FormGroup 实例。请传入一个
【发布时间】: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 那里得到了解决方案,效果很好。

标签: forms angular


【解决方案1】:

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

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

<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()">

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

【讨论】:

  • 谢谢谢谢谢谢!!!昨天我试图解决这个问题几个小时,但我无法弄清楚我做错了什么。你真的帮了大忙。
  • @JessySue 有什么办法不使用ngif。
  • 我只是忘了初始化我的FormGroup
  • 节省了我的一天,先生 ;)
  • 哈哈。谢谢@RhettHarrison
【解决方案2】:

问题是你的表单一开始是空的。

只有在 ng init 上,您才会耐心等待然后创建它。您应该在开始时初始化表单或

<section class="CreatePatient" *ngIf="patientForm">

【讨论】:

  • 我认为这一定是解决方案。因为每个表单都没有预先的值。例如login form
【解决方案3】:

面对反应式表单问题的人 首先在您的 component.ts 文件中确保您导入以下内容:

import { FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

export class NewsfeedformComponent implements OnInit {

NewsfeedForm: FormGroup;
constructor(private _formBuilder: FormBuilder){}

 ngOnInit() {

this.lookupService.getStatus().subscribe((status: IStatus) => {
  this.status = status;
});

this.NewsfeedForm = this._formBuilder.group({
  NewsfeedID: [0,null],
  StatusID: ['', Validators.required],
  publishdate: ['', Validators.required]
  })
 }

}

在你的组件 html 文件中

             <form class="form-container" [formGroup]="NewsfeedForm" 
#newsFeedform="ngForm" (ngSubmit)="form1()">

 <div id="rowTwo" fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px">
                <mat-form-field appearance="outline">
                    <mat-label>Status</mat-label>
                    <mat-select formControlName="StatusID" required>
                        <mat-option></mat-option>
                        <mat-option *ngFor="let itemofStatus of status" [value]="itemofStatus.StatusID">
                            {{itemofStatus.Status}}
                        </mat-option>
                    </mat-select>
                </mat-form-field>

                <mat-form-field appearance="outline">
                    <input matInput [matDatepicker]="publishdate" placeholder="Publish Date"
                        formControlName="publishdate">
                    <mat-datepicker-toggle matSuffix [for]="publishdate"></mat-datepicker-toggle>
                    <mat-datepicker #publishdate></mat-datepicker>
                </mat-form-field>
            </div>

【讨论】:

    【解决方案4】:

    我收到了同样的错误,初始化错误,但这是一个错字的结果。

    我写的不是ngOnInit,而是ngOninit(必须大写I

    但错误是相同的,组初始化,很难为这些类型的拼写错误确定解决方案的时间,所以我认为这可能对其他人有用。

    【讨论】:

      【解决方案5】:

      当 FormGroup 未初始化时,可能会发生此问题。请在表单标签上添加*ngIf="patientForm"

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        相关资源
        最近更新 更多