What is dependency injection (DI) in Angular?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Angular basics — a prerequisite for any developer role.
Answer
Dependency Injection (DI) is a design pattern where a class declares its dependencies (via constructor parameters) and an external system (the injector) provides them, rather than the class creating them itself. Angular has a sophisticated hierarchical DI system. Why DI? Without DI: class UserComponent { service = new UserService(new HttpClient()); } — tightly coupled, hard to test. With DI: constructor(private userService: UserService) {} — Angular creates and injects UserService automatically. How Angular DI works: (1) Service is registered in a provider (root injector, module, component); (2) When Angular creates a component, it reads constructor parameter types; (3) Angular's injector looks up the registered service for each type; (4) Creates the service (if not already created) and injects it. Injection tokens: by default, the class type is the token. Custom tokens: InjectionToken<string>("API_URL"). Provider types: useClass (default — instantiate this class), useExisting (alias for existing provider), useValue (provide a literal value), useFactory (provide via factory function — supports async and conditional creation). Hierarchical injectors: Component-level providers create new instances per component. Child components can override services. The hierarchy: root injector → module injector → component injector → child component.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Angular project, I used this when...' immediately makes your answer more credible and memorable.