What is the component injector (element injector)?
Component injector (element injector) is an injector Angular creates for each component. It handles dependencies available only to that component and its child elements.
How this works:
- each component gets its own injector when it is created;
- if providers are declared on the component, Angular stores them right there;
- when looking up a dependency, Angular goes bottom-up: first the component injector, then the module injector, then the root injector.
Example:
ts
@Component({
selector: 'app-user',
template: `<p>Profile</p>`,
providers: [UserService] // provider at the component level
})
export class UserComponent {
constructor(private userService: UserService) {}
}Here UserService is created only for this component,
and every new instance of UserComponent gets its own instance of the service.
Why it is needed:
- to isolate dependencies between components;
- so each component can have its own independent state;
- for optimization and testing, less shared data.
Summary: A component injector is a local dependency container that manages services only for a specific component and its descendants.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.