Dependency injection: Angular 22 practice questions

Dependency injection is 10% of the free Angular 22 mock (5 of 50 questions). Pick an answer to see right away whether it is correct, with the explanation and the documentation section it comes from.

NG.IV · Angular 22 practice question

A developer is building a component that needs access to both the Angular Router and a custom logging service. To obtain these dependencies directly within the component class body in modern Angular, which mechanism should they utilize?

import {Component, inject} from '@angular/core';
import {Router} from '@angular/router';
import {AnalyticsLogger} from './analytics-logger';

@Component({
  selector: 'app-navbar',
  template: `<a href="#" (click)="navigateToDetail($event)">Detail Page</a>`,
})
export class Navbar {
  private router = inject(Router);
  private analytics = inject(AnalyticsLogger);

  navigateToDetail(event: Event) {
    event.preventDefault();
    this.analytics.trackEvent('navigation', '/details');
    this.router.navigate(['/details']);
  }
}
Choose one answer
Check answer and explanation

Correct answer: By calling the inject() function directly as a class member initialization.

Explanation

The correct approach, as demonstrated in the example, is to use the inject() function directly within the component class body to retrieve the required services.

Common trap

The constructor approach is the traditional method, but the source highlights the modern capability of using inject() outside of the constructor.

Source: Angular docs: guide/di/overview — Injecting dependencies with `inject()`
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A developer is building a highly specialized checkout component that requires a unique caching mechanism for its current transaction state, ensuring that an instance on one checkout page does not affect another. To achieve this necessary isolation, where should the developer register the state management service?

import { Component } from '@angular/core';

@Component({
  selector: 'app-checkout',
  providers: [TransactionCacheService] // The service needing isolation
}) 
export class CheckoutComponent {}
Choose one answer
Check answer and explanation

Correct answer: Within the component's metadata providers array, to guarantee each instance of the component gets its own service copy.

Explanation

Registering the service in the component's metadata providers array ensures that 'Each component needs its own copy of the service,' fulfilling the requirement for isolated state.

Common trap

Registering it in the root NgModule providers array would cause all instances to share the same service instance, violating the isolation requirement. The root injector is similar to the root NgModule providers array in scope.

Source: Angular docs: Defining dependency providers — Component or directive providers
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A developer is building a large application and needs to ensure that a specific implementation of a service, like a custom LocationStrategy, is used across all parts of the application, even if individual modules might try to provide a different default. Where should this application-wide override be configured if the application is bootstrapped using `bootstrapApplication`?

bootstrapApplication(AppComponent, { providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }] });
Choose one answer
Check answer and explanation

Correct answer: Within the `providers` array of the `ApplicationConfig` passed to `bootstrapApplication`.

Explanation

The configuration should be placed in the `providers` array of the `ApplicationConfig` passed to `bootstrapApplication` because this mechanism allows application-wide providers to override existing ones.

Common trap

Placing it in `@NgModule` providers is for NgModule-based setups, not the modern standalone bootstrapping approach described, and using `providedIn: 'root'` only registers the service but doesn't guarantee overriding a specific configuration like a router strategy.

Source: Angular docs: Hierarchical injectors — Platform injector
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A developer is building a layered data access system where `BasicDataStore` relies on `AdvancedDataStore` to fetch supplemental data. How does the provided pattern ensure that `BasicDataStore` receives an instance of `AdvancedDataStore` when it is constructed?

import {inject, Service} from '@angular/core';
import {AdvancedDataStore} from './advanced-data-store';

@Service()
export class BasicDataStore {
  private advancedDataStore = inject(AdvancedDataStore);
  private data: string[] = [];

  addData(item: string): void {
    this.data.push(item);
  }

  getData(): string[] {
    return [...this.data, ...this.advancedDataStore.getData()];
  }
}
Choose one answer
Check answer and explanation

Correct answer: The `inject(AdvancedDataStore)` call within the class body automatically resolves and provides the necessary dependency instance.

Explanation

The mechanism employed utilizes the `inject(AdvancedDataStore)` invocation inside the class body to automatically obtain and supply the required dependency instance. This illustrates the contemporary approach to resolving dependencies without relying on a constructor.

Common trap

The description stating that the dependency must be explicitly passed into the constructor of `BasicDataStore` describes a different pattern, namely traditional constructor injection, which is not the technique demonstrated. Furthermore, the assertion that the `@Service()` decorator alone handles the location and instantiation of `AdvancedDataStore` is inaccurate.

Source: Angular docs: Creating and using services — Injecting into another service
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A development team is building a large Angular application and has several utility services. They are debating whether to register these services using the `providers` array within `ApplicationConfig` or by applying a specific decorator to the service class itself. Based on modern Angular practices, what is the recommended approach for these services?

import {Service} from '@angular/core';

@Service()
export class DataHelperService { /* ... */ }
Choose one answer
Check answer and explanation

Correct answer: Applying the specific decorator to the service class, as this allows optimization tools to effectively remove unused code.

Explanation

The preferred method is 'Applying the specific decorator to the service class, as this allows optimization tools to effectively remove unused code.' because the documentation indicates that employing `@Service()` enables optimization tools to perform tree-shaking, leading to reduced bundle sizes.

Common trap

The suggestion to 'Always listing the service in the `providers` array within `ApplicationConfig` to ensure global availability across all modules' is flawed because, although `ApplicationConfig.providers` can configure the injector, the documentation strongly favors the decorator for superior tree-shaking capabilities. Furthermore, the assertion that 'Using the `EnvironmentInjector` configuration exclusively, as it is the only recognized method for service provisioning' is too restrictive, as the decorator represents the preferred configuration technique.

Source: Angular docs: Hierarchical injectors — `EnvironmentInjector`
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A developer has a component, `ParentComponent`, which provides a specific instance of `LoggerService`. This component renders a child component, `ChildComponent`. If `ChildComponent` requests `LoggerService`, what is the guaranteed behavior regarding the instance it receives?

import { Component } from '@angular/core';

@Component({ selector: 'app-parent', standalone: true, template: '<div><app-child></app-child></div>' })
export class ParentComponent { provide: { LoggerService: LoggerService } };

@Component({ selector: 'app-child', standalone: true, template: '<div>...</div>' })
export class ChildComponent { constructor(public logger: LoggerService) {} };
Choose one answer
Check answer and explanation

Correct answer: The child component will receive the specific instance provided by the parent component, demonstrating override capability.

Explanation

The child component will receive the specific instance provided by the parent component, demonstrating override capability. This illustrates that child components can override providers from parent components.

Common trap

The assertion that the child component will always receive a newly created instance, regardless of the parent's provider, is incorrect because the hierarchy ensures the nearest provider is checked first. Furthermore, the claim that the child component will search up the entire application tree until it finds the first available instance, ignoring the parent's local provider, is wrong because the hierarchy dictates that the local injector is checked before moving up.

Source: Angular docs: Defining dependency providers — Injector hierarchy in Angular
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A developer has two components, Root and Child, where Child is rendered inside Root. If Child explicitly provides a specific instance of a service via its `@Component` decorator's `providers` array, what is the immediate effect when Child injects that same service?

/* Component Child */
@Component({
  selector: 'app-child',
  providers: [{provide: FlowerService, useValue: {emoji: '🌻'}}] 
})
export class Child {
  flower = inject(FlowerService);
}
Choose one answer
Check answer and explanation

Correct answer: The injector stops searching immediately upon finding the service in Child's local provider array, preventing traversal up the component tree.

Explanation

The injector halts its search as soon as it locates the required service within the Child's local provider array, thereby avoiding upward traversal through the component hierarchy.

Common trap

One description details standard dependency injection behavior without local overrides, while another assertion incorrectly claims the service will always use the root-level version, contradicting the hierarchical lookup principle when a local provider is present.

Source: Angular docs: Hierarchical injectors — Using the `providers` array
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A library author is building a reusable module and needs to expose a configurable service. They are debating between providing a static configuration object versus using a provider function pattern. According to modern Angular best practices, what is the primary advantage of using the provider function approach?

Choose one answer
Check answer and explanation

Correct answer: It allows the library to hide its internal implementation details while still allowing consumers to customize behavior using composition patterns.

Explanation

The provider function approach ensures that "Internal tokens and implementation details remain private" while enabling flexible composition.

Common trap

The guarantee that "the service will always be instantiated only once, regardless of how many components request it" describes singleton behavior, which is often desired but not the unique benefit highlighted by using provider functions over direct configuration. The claim that "it simplifies the build process by automatically optimizing all dependency imports at compile time" relates to build optimization, which is not the focus of this DI pattern.

Source: Angular docs: Defining dependency providers — Why use provider functions instead of direct configuration?
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A developer needs to conditionally instantiate a service implementation based on an environment flag read during injection. Which dependency injection mechanism should they employ to achieve this dynamic instantiation?

import {inject, InjectionToken, Service} from '@angular/core';

@Service({
  factory: () => (inject(ANALYTICS_ENABLED) ? new GoogleAnalytics() : new Analytics()),
})
export class Analytics { /* ... */ }
Choose one answer
Check answer and explanation

Correct answer: Using the `factory` option on the service metadata, which allows reading other dependencies via `inject()` within the factory function.

Explanation

The `factory` option allows the developer to execute a function that can use `inject()` to check environment tokens and return the appropriate class instance, fulfilling the requirement for conditional instantiation.

Common trap

The `useFactory` option is part of `@Injectable` but the source explicitly states that `factory` replaces the use of `@Injectable` options like `useFactory` when custom instantiation logic is needed.

Source: Angular docs: Creating and using services — Replacing the implementation with a factory
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A developer needs to create a reusable data management class in an Angular application. They have two options: using the CLI or manual definition. Which approach allows them to clearly signal to the Angular framework that this class should be managed as a dependency?

import {Service} from '@angular/core';
@Service()
export class DataManager { /* ... */ }
Choose one answer
Check answer and explanation

Correct answer: Manually adding the @Service() decorator to the class definition.

Explanation

Manually adding the @Service() decorator to the class definition tells Angular that the class is an injectable dependency, as shown in the example provided.

Common trap

Running the CLI command alone doesn't guarantee the dependency registration needed for injection; while it creates the file, the decorator is what explicitly marks it for DI. The @Injectable() decorator is for general dependency injection, but the source specifically mentions @Service() for this context.

Source: Angular docs: Creating and using services — Creating a service
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


NG.IV · Angular 22 practice question

A service needs to utilize multiple distinct authorization handlers, each registered under the same injection token. To ensure the service receives an array containing all registered handlers, what must be true about the provider configuration for each handler?

providers: [
  {provide: AuthToken, useClass: HandlerA, multi: true},
  {provide: AuthToken, useClass: HandlerB, multi: true}
]
Choose one answer
Check answer and explanation

Correct answer: The token must be defined as an InjectionToken, and each provider must include the 'multi: true' flag.

Explanation

The proper setup mandates declaring the token and ensuring that every provider supplying that token includes the 'multi: true' attribute, leading to the injection of an array.

Common trap

The suggestion that providers must be listed in order, allowing the injection mechanism to automatically combine them, is flawed because Angular necessitates the explicit 'multi: true' flag to gather multiple instances under a single token.

Source: Angular docs: Defining dependency providers — Multiple providers
Checked against the cited text on 2026-11-25.

Report an error in this question

Open this question on its own page


Back to all topics