错误formControlName必须与父formGroup指令一起使用。您需要添加一个formGroup

时间:2019-12-14 12:33:01

标签: angular

我是angular 8的新手,目前,我正尝试将一个旧项目从angular Js迁移到angular,在我得到可怕的Error formControlName必须与父formGroup指令一起使用之前,一切都很好。您将要添加一个formGroup。...

我已经阅读并尝试了几乎所有找到的解决方案,但没有Joy。希望有一个仁慈的灵魂可以帮助我吗?

问题摘要。 我的登录,注册和忘记通过表单都使用相同的方法并且工作正常,但是我完整应用程序内部的表单会抛出该错误。

我尽可能地简化了代码,以便于理解 我的应用程序组织如下:

app
app.component.html
app.module.ts
app-routing.module.ts
----authentication
-------Login,forgotpass, register at the same level but different directories
    authentication-routing.module.ts
    authentication-module.ts
Layout
-----header,footer,sidebar register at the same level different directories
layout-routing.module.ts
layout.module
home
-----home.component, home.module, home.component.ts
mypaymentreq
----Newrequest
    -----Newrequest.component.html,newrequest.component.ts at same level
mypaymentreq-routing.module.ts

mypaymentreq-module.ts

newrequest.component.ts看起来像:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { User} from '../../_models';
import { AlertService, UserService, AuthenticationService } from '../../_services';
@Component({
    selector: 'app-newrequest',
    templateUrl: './newrequest.component.html',
    styleUrls: ['./newrequest.component.css']
})
export class NewrequestComponent implements OnInit {
currentUser: User;
mypaymentrequestForm: FormGroup;
loading = false;
submitted = false;

constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService,
    private userService: UserService,
    private alertService: AlertService
    ) {
       this.currentUser = this.authenticationService.currentUserValue;
   }

ngOnInit() {
    this.mypaymentrequestForm = this.formBuilder.group({
        employeeName: [''],
        dateRequest: [''],
        ...(many more values will go here once I sort out isse)
     })
}


onSubmit() {
    this.submitted = true;
    ......
    }
   }

newrequest.component.html代码如下:

<body>
    <div id="wrapper">
        <SidebarComponent></SidebarComponent>
           <div id="page-wrapper" class="gray-bg">
              <HeaderComponent></HeaderComponent>
                <div class="row wrapper border-bottom white-bg page-heading">
                <div class="col-sm-4">
                    <h2>Payment Request </h2>
                        <ol class="breadcrumb">
                        <li class="breadcrumb-item">
                            <a href="/home">Home</a>
                         </li>
                        <li class="breadcrumb-item active">
                            <strong>Payment Request</strong>
                        </li>
                    </ol>
                </div>
            </div>
        <div class="wrapper wrapper-content animated fadeInRight">
            <div class="col-lg-12">
                <div class="ibox-content m-b-sm border-bottom">
                    <div class="p-xs">
                        <div class="float-left m-r-md">
                            <i class="fa fa-home text-navy mid-icon"></i>
                        </div>
                        <h2><font color="#4eccb9"  class="font-weight-bold"></font></h2>
                        <span></span>
                    </div>
                </div>
                <div class="ibox-content forum">
                    <div class="col-lg-12">
                        <div class="ibox-title">
                            <h5></h5>

                        </div>
                        <div class="ibox-content">
                            <form class="container" [formGroup]="mypaymentrequestForm"   (ngSubmit)="onSubmit()">
                                <label class="col-sm-10 col-form-label">*Employee Making Request</label>
                                <input id="employeeName" formControlName="employeeName" type="text" placeholder="" class="form-control" required>
                                <label class="col-sm-10 col-form-label">Date of Request</label>
                                <input id="theDate" formControlName="dateRequest" type="text" class="form-control" >
                                <button class="btn btn-primary btn-sm">Submit</button>  
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <FooterComponent></FooterComponent>
    </div>
</div>


请注意,正确显示了currentUser.firstname和currentUser.lastname的值。

mypaymentreq-routing.module.ts如下:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NewrequestComponent } from './newrequest/newrequest.component';
import { ModuleWithProviders } from '@angular/core';
export const routes: Routes = [
  { 
    path: '', component: NewrequestComponent,  canActivate: [AuthGuard],   
  },
{ 
   path: 'newrequest', component: NewrequestComponent,  canActivate: [AuthGuard],   
},]
export const routing: ModuleWithProviders = RouterModule.forChild(routes)

mypaymentreq.module.ts如下:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NewrequestComponent } from './newrequest/newrequest.component';
import { routes } from './mypaymentreq-routing.module';
import { RouterModule } from '@angular/router';
import { LayoutModule } from '../layout/layout.module';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { HomeModule } from '../home/home.module';


@NgModule({
  declarations: [NewrequestComponent],
  imports: [
  CommonModule,
  RouterModule.forChild(routes),
  LayoutModule,
  HomeModule,
  ReactiveFormsModule,
  FormsModule
],

})
export class MypaymentreqModule { }
--------------------------------------

app.module.ts看起来像:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AuthenticationModule } from './authentication/authentication.module'
import { ReactiveFormsModule, FormsModule} from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { routing } from './app-routing.module';
import { JwtInterceptor, ErrorInterceptor } from './_helpers';
import { AppComponent } from './app.component';
import { HomeModule } from './home/home.module';
import { AlertModule } from './_components/alert.module';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { MypaymentreqModule } from './mypaymentreq/mypaymentreq.module'


@NgModule({
    imports: [
       BrowserModule,
       routing,
       ReactiveFormsModule,
       FormsModule,
      HttpClientModule,
      HomeModule,
      AuthenticationModule,
     RouterModule,
     AlertModule,
     MypaymentreqModule
  ],
declarations: [
    AppComponent,
],
providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },


],
schemas : [NO_ERRORS_SCHEMA],

bootstrap: [AppComponent]
})

导出类AppModule {};     -------------------

the app-routing.module.ts looks like
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home';
import { AuthGuard } from './authentication';
import { ModuleWithProviders } from '@angular/core'

export const routes: Routes = [
{
  path: '',
  redirectTo: 'login',
  pathMatch: 'full'
},
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', loadChildren: './authentication/authentication.module#AuthenticationModule', },
{ path: 'register', loadChildren: './authentication/authentication.module#AuthenticationModule', },
{ path: 'forgotpass', loadChildren: './authentication/authentication.module#AuthenticationModule', 
},
{ path: 'newrequest', loadChildren: './mypaymentreq/mypaymentreq.module#MypaymentreqModule', },


// otherwise redirect to home
{ path: '**', redirectTo: 'login' }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes)

 --------------------------------------

完整错误是:

ERROR Error: formControlName must be used with a parent formGroup directive.  
 You'll want to add a formGroup
   directive and pass it an existing FormGroup instance (you can create one in your class).

  Example:


<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});
at Function.controlParentException (forms.js:2237)
at FormControlName._checkParentType (forms.js:8061)
at FormControlName._setUpControl (forms.js:8069)
at FormControlName.ngOnChanges (forms.js:7993)
at checkAndUpdateDirectiveInline (core.js:31906)
at checkAndUpdateNodeInline (core.js:44367)
at checkAndUpdateNode (core.js:44306)
at debugCheckAndUpdateNode (core.js:45328)
at debugCheckDirectivesFn (core.js:45271)

at Object.eval [作为updateDirectives]

这是我第一次在这个论坛上提问,如果真的很愚蠢,我很想念... :-),但是经过2天多的尝试之后,其他人会提出意见也许对我来说最好的事情。

2 个答案:

答案 0 :(得分:0)

初始化控件。

this.mypaymentrequestForm = this.formBuilder.group({
        employeeName: this.formBuilder.control(''),
        dateRequest: this.formBuilder.control(''),
        ...(many more values will go here once I sort out isse)
     })

答案 1 :(得分:0)

发现了问题,因为html代码是我要升级的旧代码,所以我没有注意到在htlm页面的顶部存在以下内容 元formControlName =“ viewport” content =“ width = device-width,initial-scale = 1.0” 我不确定该代码如何到达那里,但是一旦我将其固定为以下内容: meta name =“ viewport” content =“ width = device-width,initial-scale = 1.0” 整个工作正常,谢谢您的帮助