📎 Webclip
Fascinating Dependency Injection
Angular dependency injection is presented as a hierarchical system tied to the DOM, where the same token can resolve to different instances depending on context. The article then shows how different provider strategies and factory-based resolution can be used to keep code flexible, reduce boilerplate, and handle cases that are awkward with inputs alone.
Reading notes#
- DI is described as a hierarchical lookup system, not a simple pool of objects, and the nearest element injector is checked first.
- Each rendered HTML element gets its own
ElementInjector, which explains why the sameElementRefcan refer to different native elements in different places. - If a token is not found in the current injector, Angular walks up through parent injectors, then the root injector, then the platform injector, and finally the
NullInjector. - This lookup behavior is compared to JavaScript prototype inheritance.
- A class can be provided with the shorthand
providers: [SomeService], which is equivalent touseClass. useValueis shown as a way to provide environment data through DI while keeping type safety.useExistingcan expose only a limited shell API while delegating to a fuller third-party service.useFactorycan choose an implementation at runtime, such as returning different logger services depending on the environment.- A factory can also use
ActivatedRouteand query parameters to choose between anIncomeServiceand anExpensesServicefor a component. - Abstract classes are used as DI tokens for transaction services because interfaces disappear at compile time.
- A shared registration form can be passed through a custom injection token instead of an input, preserving stronger typing and avoiding input-related complexity.
- If a child component only ever appears inside one parent, it can inject the parent component directly and access the parent’s form.
- A global loading text can be provided through an optional injection token so consumers can override the default text without affecting explicit component input values.
- The article closes by framing these DI patterns as underused but useful for large Angular applications.
