繁体   English   中英

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

[英]Error formControlName must be used with a parent formGroup directive. You'll want to add a formGroup

我是 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

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)

在 Object.eval [作为 updateDirectives]

这是我第一次在这个论坛上提问,如果我遗漏了一些非常愚蠢的东西,请善待你的回答...:-) 但是经过 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)
     })

发现问题,由于 html 代码是我正在升级的遗留代码,我没有注意到在 htlm 页面的顶部出现了以下内容 meta formControlName="viewport" content="width=device-width, initial- scale=1.0" 我不确定该代码是如何到达那里的,但是一旦我修复了该行以读取:meta name="viewport" content="width=device-width, initial-scale=1.0" 整个工作正常,谢谢为了帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM