7

I'm getting really fustrated because I have no idea what's happening. Everything worked correctly this morning right before some changes I made to merge together 2 forms in a ReactiveForm and now I get the following error in the browser:

Error: StaticInjectorError(AppModule)[FormGroup]:
StaticInjectorError(Platform: core)[FormGroup]: NullInjectorError: No provider for FormGroup! Error: StaticInjectorError(AppModule)[FormGroup]:
StaticInjectorError(Platform: core)[FormGroup]: NullInjectorError: No provider for FormGroup!

I'm importing FormsModule and ReactiveFormsModule in my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
[...]
@NgModule({
  declarations: [
    AppComponent,
    CustomersComponent,
    HeaderComponent,
    CustomersListComponent,
    CustomerEditComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    ...
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And then the FormGroup in my component:

import { FormGroup, FormControl, Validators } from '@angular/forms';
[...]

And declaring a new FormGroup afterwards in the component. I tried to reinstall the @angular/forms package with npm but I'm still getting the error... I've seen some similar questions asked but from what I could tell, it was related with the testing environment. If you have any idea, thanks in advance.

Martin Carre
  • 1,157
  • 4
  • 20
  • 42

3 Answers3

15

Don't inject FormGroup into the constructor of the component.

This it's NOT ok:

constructor(private fb:FormBuilder,  private ts:FormGroup)

This its ok:

constructor(private fb:FormBuilder)
Tomislav Stankovic
  • 3,080
  • 17
  • 35
  • 42
Frank
  • 403
  • 3
  • 10
0

I would have to see your ts file where the form is being built. But it sounds like you are using Reactive Forms and have not imported everything needed. ReactiveForms requires not only:

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

but also be sure to import "FormBuilder" in that same import statement:

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

also, in your constructor you should have similar to the following :

constructor(private fb: FormBuilder) {} 

and the form should have the form builder instantiating the form:

productForm = this.fb.group({})

If that doesn't fix the issue, I would need to see more to help.

Jeran
  • 41
  • 6
0

This problem happens when the input is not a form control, which is not related to any Angular version or Form Builder.

To solve this apply either of the below solutions,

  1. form: FormGroup | any
  2. add "strictPropertyInitialization": false, in tsconfig.json file .

It got resolved for me like this :)

Neha Prajapati
  • 111
  • 2
  • 3