【问题标题】:Error formControlName must be used with a parent formGroup directive. You'll want to add a formGroup错误 formControlName 必须与父 formGroup 指令一起使用。您需要添加一个 formGroup
【发布时间】:2020-04-07 15:32:46
【问题描述】:

我是 angular 8 的新手,此时,我正在尝试将一个旧项目从 angular Js 迁移到 angular,并且在我得到可怕的错误 formControlName must be used with a parent 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

新的request.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)

在 Object.eval [as updateDirectives]

这是我第一次在这个论坛上提问,如果我想念的东西真的很愚蠢,请善待你的回答...:-) 但是经过 2 天以上的尝试,其他人的观点也许对我来说是最好的。

【问题讨论】:

  • 欢迎来到 SO。你能分享更多newrequest.component.html的代码
  • 您的 newrequest.component.html 中的
    标记之外似乎有一个 formControlName。
  • 根据要求添加了完整的html
  • 你好 Fateme,我的 FormcontrolName 在外面是什么意思?
  • 准确完整的错误信息是什么?它指的是哪个文件和该文件中的哪一行?为什么你的 HTML 模板中有 body 标签?

标签: angular


【解决方案1】:

发现问题,因为 html 代码是我正在升级的旧代码,我没有注意到在 htlm 页面顶部存在以下内容 meta formControlName="viewport" content="width=device-width, initial-scale=1.0" 我不确定该代码是如何到达那里的,但是一旦我修复了该行以读取: 元名称=“视口”内容=“宽度=设备宽度,初始比例=1.0” 一切正常,感谢您的帮助

【讨论】:

    【解决方案2】:

    初始化您的控件。

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

    【讨论】:

    • 您好 Francesco,按照建议更改代码并没有解决问题..
    • Hell Jb Nize,body 标签从代码的早期就一直存在,并且认为它不会对 angular 产生影响...按要求添加了完整的错误
    猜你喜欢
    • 2017-09-04
    • 2018-01-31
    • 2018-10-03
    • 2018-03-09
    • 2020-02-06
    • 2019-09-28
    • 2020-01-25
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多