Angular7: NullInjectorError: No provider for FormGroup

Ardzii picture Ardzii · May 6, 2019 · Viewed 8.5k times · Source

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.

Answer

Frank picture Frank · Apr 21, 2020

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)