Class constructor injection - lordoftheflies/angular-essential-training GitHub Wiki

There are two pieces to the puzzle to do constructor injection at a class level for components, directives and pipes, the import statement and constructor parameters with type annotation. Let's refactor the media item form component class to use the form builder class to help in the creation of the form model to see constructor injection in action. The form builder is a class provided in the Angular platform that has a group method on it for building a form group. It can be found in the Angular forms scoped package. So, we can add that to the existing import statement. We import this type so we can use it in the TypeScript type annotation syntax in the constructor signature. Let's create a constructor and add a form builder parameter with typing (typing) This is a bit of TypeScript here, the colon followed by the type. Under the hood, the TypeScript is getting transpiled into JavaScript that handles these types in combination with the decorator to inform Angular what the parameters of the constructor should be. It's a bit complicated, but by leveraging TypeScript when you write code for your Angular app that complication is abstracted away and implementation becomes more lightweight. We need to use the form builder in the ngOnInit method. So we need to store it in a property on the component class from the constructor. We can leverage a bit of TypeScript here for that as well. By using the private access modifier in front of the parameter name TypeScript will create the property and set it for us when it transpiles to JavaScript. Now we can refactor the ngOnInit method to use the injected form builder and call the group method on that, replacing the new form group instantiation. (typing) The form builder also has a control method for creating new form control objects. So we can replace the new form control instantiations in here as well using the control method for those. (typing) Not only did we do some constructor injection here, but we also brought in a service instance to help us build the form allowing us to remove the instantiation calls from within our component. This ultimately leads to better decoupled code and is one of the big benefits of dependency injection and inversion of control.