Search code examples
angularangular-formbuilder

Why was the Angular FormBuilder created as a service?


I was looking at the FormBuilder Source Code and noticed that there's nothing stopping it from being just a regular class that could be constructed in a component.

Why did they decide to make it an injectable service?


Solution

  • Good question. Simply, to decrease coupling. I can think of three reasons:

    First, to be consistent. All the util services in Angular are injectable. If you need something from Angular, you just inject it to use it.

    Second, and the most important, to be future compatible. Let's say someday, Angular team decided that FormBuilder has a constructor that expects another service. For example:

    export class FormBuilder {
      constructor(private someInternalService: SomeInternalService)
    }
    

    Because the FormBuilder is injectable, they can add the internal service without worrying about breaking compatibility in their future version.

    Lastly, this will also enable you to extend your own version of FormBuilder. Let's say you want to create a router-aware FormBuilder. You can simply extend the FormBuilder, and provide it in some @NgModule. Hereafter, you can use your own version of the FormBuilder without breaking anything.