3
votes

the Angular documentation on dependency injection has confused me.
I understand that Angular DI works by specifying to the DI (the injector) something to "provide" via the providers array on the metadata object passed to NgModule (for the whole module) or Component (for just that component).

This question is not specific to reactive forms, but in the angular.io example for Reactive Forms it has the component defined as (simplified!):

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

@Component({
  template: '<p>Hello world</p>'
})
export class DepInjectionExample
{
     constructor(private formBuilder: FormBuilder)
     {
        //Use form builder here
     }
}

Now this works (I have a reactive form working), but how? There is no "provider" for FormBuilder, either in the Component providers array or its containing NgModule providers array. Yet the Angular DI documentation is insistent the providers array is the only way to register something for DI. What's going on? How can some injected things not need to be in the providers array?

Thanks in advance.


UPDATE with answer

Ah! I see from the providers page: "when you import a module that has providers, those providers are also available to all the classes in the app as long they have the lookup token. For example, if you import the HttpClientModule into your AppModule, its providers are then available to the entire app and you can make HTTP requests from anywhere in your app." https://angular.io/guide/providers

I did not realise that an imported module's providers automatically became providers for the importing module.

1
Look at this github.com/angular/angular/blob/master/packages/forms/src/… so if you import ReactiveFormsModule you will be able to inject FormBuilderyurzui
Thanks for the comment, but why is it that something that is part of something that is imported becomes available to the DI/an injector? My question is not "how to get Reactive Forms working", it's how can I be injecting without a provider?user603563

1 Answers

1
votes

The ReactiveFormsModule provides the FormBuilder Service. So, when you imports: [ReactiveFormsModule] in your module you are providing FormBuilder too.

The FormBuilder is a feature of ReactiveFormsModule. It is like any other module that you add to your application. Another one that you can see this behaviour is MatDialog service that is provided by MatDialogModule.

This is the Module pattern used by Angular. We use modules to GROUP FEATURES as (service, pipe, directive, routes and components) and its dependencies.

In the docs they say:

NgModules configure the injector and the compiler and help organize related things together.

As the user pointed out: "imported module's providers automatically became providers for the importing module."