'NullInjectorError: No provider for FormBuilder

I need to use FormBuilder but the program gives me some error. This is a module that I can export from other component:

the module.ts is

@NgModule({
    imports: [
        CommonModule,
        ReactiveFormsModule,
        FormsModule,
        DialogModule,
        ButtonModule,
        InputTextModule,
        TableModule,
        MessageModule

    ],
    declarations: [
        SearchCodeComponent
    ],
    exports: [
        SearchCodeComponent
    ],
    providers: []

})

export class SearchCodeModule { }

In my html i do:

  <form [formGroup]="descriptionForm" (ngSubmit)="onSubmit()">
...
..
<input formControlName="code">..

In my ts I do:

 descriptionForm: FormGroup

The problem is that when I go on the page I obtain two exception

ERROR NullInjectorError: R3InjectorError(AppModule)[FormBuilder -> FormBuilder -> FormBuilder]: 
  NullInjectorError: No provider for FormBuilder!

and other is:

 ASSERTION ERROR: Reached the max number of directives [Expected=> 4 != 4 <=Actual]

Anyone know how can I resolve this?



Solution 1:[1]

It seems that you are importing ReactiveFormsModule in your AppModule. Remove it from your main AppModule import.

Check this thread on github, it contains some other possible ways to resolve this problem https://github.com/angular/angular/issues/31221#issuecomment-617474627

Solution 2:[2]

In your TS file you need to initialize your form group (as per NullInjectorError). One way is to initialize it inside ngOnInit(){} function. This gives you more control if you have more items in form.

ngOnInit(){
this.descriptionForm = new FormGroup({
    code: new FormControl('')
  });
};

or else you can do the following in TS file where you are declaring descriptionForm

descriptionForm: FormGroup  = new FormGroup({
        code: new FormControl('')
      }); 

Hope this helps :)

Solution 3:[3]

add this in component.modul.ts :

import { ReactiveFormsModule } from '@angular/forms';

imports: [ ReactiveFormsModule

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrei Mihalciuc
Solution 2 Kishor Kunal
Solution 3 King Kapeta