NullInjectorError: No provider for FormBuilder

Viewed 5642

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?

3 Answers

add this in component.modul.ts :

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

imports: [ ReactiveFormsModule

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 :)

Related