Created by
Enea Jahollari Kevin Kreuzer Ilir Beqiri
In Angular v14, inject() function was introduced as a new way to inject dependencies into Angular components, directives, services, and other classes. This new function is more flexible and provides a better way to inject dependencies compared to the previous way of using constructor dependency injection.
How it works?
The moment you run the schematics, it will look for all the classes that have dependencies injected in the constructor and convert them to use the inject() function.
It will keep the same order of the dependencies.
It will keep the same type of the dependencies.
It will keep the same visibility of the dependencies.
It will keep the same decorators (converted into options) of the dependencies.
It will use the correct way of injecting the dependencies when injecting generic types.
It will skip constructors that have no dependencies.
It will cleanup empty constructors.
It will add ‘this’ keyword to the dependencies that are not using it inside the constructor body.
It will add the ‘inject’ import statement to the file if it’s not already imported.
Example:
Before running the schematics:
After running the schematics:
Options
--project: Specifies the name of the project.
--path: Specifies the path to the file to be migrated.
--includeReadonlyByDefault: Specifies whether to include the readonly keyword by default for the injections. Default is false.
--useESPrivateFieldNotation: Specifies whether to replace TS private modifier with ES #private field notation. Default is false.
Include readonly by default
By default, the migration will not add the readonly keyword to the injected dependencies. If you want to add the readonly keyword to the injected dependencies you can set the --includeReadonlyByDefault option to true.
Use ES private field notation
By default, the migration will keep the private keyword to the injected dependencies. If you want to replace TS private modifier with ES #private field notation to the injected dependencies you can set the --useESPrivateFieldNotation option to true.
Usage
In order to run the schematics for all the project in the app you have to run the following script:
If you want to specify the project name you can pass the --project param.
If you want to run the schematic for a specific component or directive you can pass the --path param.
Usage with Nx
To use the schematics on a Nx monorepo you just swap ng with nx