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