What is Dependency Injection (DI) in Angular? Why is the DI mechanism needed?
Dependency Injection (DI) is a mechanism Angular uses to automatically supply the needed dependencies (for example, services) to components, directives, or other classes.
In simple terms:
Instead of creating objects manually with new, Angular creates and supplies them itself when they are needed.
Example:
ts
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-profile',
template: `{{ userService.userName }}`
})
export class ProfileComponent {
constructor(public userService: UserService) {}
}Here UserService is automatically created by Angular and passed into the component's constructor.
You do not need to write new UserService() - Angular already knows how to do it.
Why DI is needed:
- Less coupling. Components do not know how services are created, only that they exist.
- Easier to test. Dependencies can be swapped for fakes (mocks).
- Reusability. One service can be used in multiple places.
- Lifetime management. Angular decides when to create and destroy dependencies.
Summary: Dependency Injection is a way for Angular to take over creating and supplying the needed objects, so the code stays cleaner, more flexible, and easier to maintain.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.