3

I was reading through a really well written article about Angular's module loading here - https://medium.com/@cyrilletuzi/understanding-angular-modules-ngmodule-and-their-scopes-81e4ed6f7407

Since providers at feature modules' NgModule are actually injected globally (and eagerly), the article talks about the "forRoot" pattern used in modules like RouterModule.

I came across ReactiveFormsModule - https://angular.io/api/forms/ReactiveFormsModule - which has the FormBuilder provider, but it doesn't seem to use the forRoot pattern. Doesn't this mean every feature module using ReactiveFormsModule will end up re-creating the FormBuilder provider? Am I missing something?

1

1 Answer 1

4

forRoot is only relevant for lazy-loaded modules. For eager loaded modules, providers are registered in the application root scope anyway.

If you have imported ReactiveFormsModule in lazy loaded modules, then a FormBuilder instance per lazy-loaded module would be created. It doesn't really matter thought, because FormBuilder doesn't have a state. So not being singleton doesn't make a difference for how FormBuilder works and because it doesn't have a state, it also doesn't make a difference memory-wise.

Sign up to request clarification or add additional context in comments.

2 Comments

Makes sense. If I understood it right, adding forRoot to ReactiveFormsModule won't affect the behavior either. But for modules with services that have state, lazy loading can make a difference as injection happens at feature module level in that scenario. Pls correct me if I am wrong.
It definitelly makes a difference if you want a single application-global service instance. Lazy loaded modules introduce a child-scope where they register their service providers, this results in a service instance per lazy loaded module instance and the service won't be available to non-lazy-loaded modules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.