How do I fix the error "No provider for UntypedFormBuilder" in Angular?
How do I fix the error "No provider for UntypedFormBuilder" in Angular?
The "No provider for UntypedFormBuilder" error in Angular typically arises when Angular cannot find the UntypedFormBuilder service in the dependency injection system for the component or module where you're using it. This usually occurs when you're using Angular versions 14 or later, where FormBuilder was renamed to UntypedFormBuilder.
Here's a breakdown of common causes and solutions:
-
Using
UntypedFormBuilderwithout importingReactiveFormsModule:The
UntypedFormBuilderservice is provided by theReactiveFormsModule. If you're using reactive forms but haven't imported this module, Angular won't be able to find theUntypedFormBuilder.Solution:
Import
ReactiveFormsModuleinto the relevant module (typically yourAppModuleor a feature module). For example:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ReactiveFormsModule // Import ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } -
Typos or incorrect imports:
Double-check that you've imported
UntypedFormBuildercorrectly and that there are no typos in the import statement or when referencing the class.Solution:
Make sure your import statement looks like this:
import { UntypedFormBuilder } from '@angular/forms';And that you are using it correctly in your constructor:
constructor(private fb: UntypedFormBuilder) { } -
Incorrect module scope:
If you are using
UntypedFormBuilderin a lazy-loaded module, ensure thatReactiveFormsModuleis imported into that specific lazy-loaded module as well, and not just the rootAppModule.Solution:
Import
ReactiveFormsModulein the module that declares the component usingUntypedFormBuilder. -
Conflicting Angular versions (unlikely but possible):
In rare cases, discrepancies in Angular versions between different parts of your project could cause issues. This is less common but worth considering if other solutions don't work.
Solution:
Ensure all your Angular dependencies are aligned to the same version. Use
npm list @angular/core(and other @angular packages) to check versions. Update dependencies usingng update.