InterviewHubPRO
Section Overview
Q17

Question 17 of 283

Part 1: Architecture, Components, Directives & Lifecycle (1 - 35)

6%
Angular & Signals (283 Qs)•Part 1: Architecture, Components, Directives & Lifecycle (1 - 35)

What is dependency injection in Angular?

Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.

Practical Code Example

typescript
// Dependency Injection: Injecting services via constructor or modern inject() function
import { Component, inject } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-profile',
  standalone: true,
  template: `<div>User: {{ user().name }}</div>`
})
export class ProfileComponent {
  // Modern Angular 14+ inject() pattern:
  private userService = inject(UserService);
  user = this.userService.currentUser;
}