FresherTechnicalAngular
What is dependency injection in Angular and why is it used?
Try answering first
Model answer
Dependency injection (DI) means a class does not create the things it depends on. It asks for them, and Angular's injector creates and supplies them. A class declares what it needs, and the framework decides how to build it.
@Injectable({ providedIn: 'root' })
export class Logger {
log(message: string) {
console.log(message)
}
}
@Component({ selector: 'app-home', template: `<p>Home</p>` })
export class Home {
private logger = inject(Logger)
constructor() {
this.logger.log('Home created')
}
}
providedIn: 'root' registers one shared instance (a singleton) for the whole app, and unused services can be removed from the bundle (tree-shaking).
DI is used because it:
- Avoids hard-coded
newcalls, so classes are loosely coupled. - Makes testing easy, since you can swap a service for a fake.
- Lets you control the scope: app-wide, per route or per component.
Older code injects through constructor parameters, which does the same thing.
Ask for dependencies instead of creating them.
Key points
- Classes ask for dependencies; the injector supplies them
- providedIn root creates a shared singleton
- DI makes testing and swapping implementations easy
- Scope can be app, route or component
Likely follow-ups
- What happens if Angular cannot find a provider for a service?
Common mistakes
- Creating services with new instead of injecting them
- Forgetting Injectable and a provider so injection fails