Sub topic 4
Initializing a Component with ngOnInit
This chapter assumes you can write a standalone Angular component with inputs, know the basics of RxJS subscriptions, and have read the chapter on constructor versus ngOnInit. Here you will learn exactly when ngOnInit runs, what it is good for, and where it stops being the right tool.
What ngOnInit guarantees
ngOnInit is called once per component instance. Angular calls it after the first ngOnChanges, or directly after the constructor if the component has no bound inputs. At that point:
- Input values bound in the parent's template are already assigned.
- Injected dependencies are available (they were available in the constructor too).
- The component's own view and its projected content do not exist yet.
The hook never runs a second time for the same instance. If Angular destroys the component and later creates a new one, for example when an @if block toggles or a route is revisited, the new instance gets its own ngOnInit.
Implementing the OnInit interface is optional at runtime, because Angular looks for a method named ngOnInit. Declaring implements OnInit still helps, since the compiler then catches a misspelled method name.
A typical use: loading data
The most common job for ngOnInit is to start work that depends on input values. The example below loads a user when the component is created.
import { Component, DestroyRef, Injectable, Input, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Observable, delay, of } from 'rxjs';
export interface User {
id: string;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
load(id: string): Observable<User> {
return of({ id, name: `User ${id}` }).pipe(delay(300));
}
}
@Component({
selector: 'app-user-profile',
standalone: true,
template: `
@if (user) {
<h2>{{ user.name }}</h2>
} @else {
<p>Loading…</p>
}
`,
})
export class UserProfileComponent implements OnInit {
@Input({ required: true }) userId!: string;
user: User | null = null;
private readonly users = inject(UserService);
private readonly destroyRef = inject(DestroyRef);
ngOnInit(): void {
this.users
.load(this.userId)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((user) => (this.user = user));
}
}Two details matter here. First, this.userId is safe to read because inputs are set before ngOnInit. In the constructor it would still be undefined. Second, takeUntilDestroyed is given this.destroyRef explicitly. Called without an argument, it needs an injection context, and ngOnInit is not one. Calling it bare inside this hook throws a runtime error.
What belongs in ngOnInit
| Work | Where it goes | Reason |
|---|---|---|
| Assign field defaults | Field initializer or constructor | No inputs needed |
| Read inputs once and start a request | `ngOnInit` | Inputs are set |
| React to every input change | `ngOnChanges` or signals | `ngOnInit` runs only once |
| Read `@ViewChild` results | `ngAfterViewInit` | Views are not created yet |
| Read `@ContentChild` results | `ngAfterContentInit` | Projected content is not ready |
| Measure or focus DOM elements | `afterNextRender` | Needs a rendered browser DOM |
A useful rule: keep the constructor for dependency injection and trivial assignments, and put anything that reads inputs or causes side effects in ngOnInit.
Edge cases and gotchas
Later input changes do not re-run it
In the example above, if the parent changes userId from '1' to '2', ngOnInit does not run again and the old user stays on screen. Any work that must follow an input has to live in ngOnChanges (or in a signal-based approach covered later in this tutorial).
Because ngOnChanges fires before ngOnInit on the first pass, you can move the loading entirely into ngOnChanges and handle both cases. Cancelling the previous request also prevents a slow, older response from overwriting a newer one.
import { Component, DestroyRef, Input, OnChanges, SimpleChanges, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subscription } from 'rxjs';
import { User, UserService } from './user-profile.component';
@Component({
selector: 'app-user-profile-live',
standalone: true,
template: `
@if (user) {
<h2>{{ user.name }}</h2>
} @else {
<p>Loading…</p>
}
`,
})
export class UserProfileLiveComponent implements OnChanges {
@Input({ required: true }) userId!: string;
user: User | null = null;
private readonly users = inject(UserService);
private readonly destroyRef = inject(DestroyRef);
private request?: Subscription;
ngOnChanges(changes: SimpleChanges): void {
if (changes['userId']) {
this.request?.unsubscribe();
this.user = null;
this.request = this.users
.load(this.userId)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((user) => (this.user = user));
}
}
}Async ngOnInit is not awaited
You can write async ngOnInit(), and it will compile. Angular still does not wait for the returned promise. The first render happens right after the synchronous part finishes, and a rejected promise is not reported through Angular's normal error path. Design the template to handle the "no data yet" state, as the @else branch does above.
Errors stop initialization
An exception thrown inside ngOnInit is reported to Angular's ErrorHandler, and the component's remaining hooks and rendering for that pass are disrupted. Catch errors from risky synchronous work, and use catchError in observable pipelines so a failed request becomes an error state instead of a broken component.
It also runs during server-side rendering
When the app is rendered on the server, ngOnInit executes there too. Code that touches window, document or localStorage will fail on the server. Keep such code out of ngOnInit, or move it into afterNextRender, which only runs in the browser.
Parents initialize before their children exist
A parent's ngOnInit runs before Angular creates the child components in the parent's template. A parent therefore cannot ask a child to do something from its own ngOnInit. Parent-to-child ordering is covered in a later chapter.
In tests, it waits for the first detectChanges
With TestBed, createComponent only constructs the component. ngOnInit runs on the first fixture.detectChanges(). If you set inputs with fixture.componentRef.setInput('userId', '7') before that first call, the hook sees the values you set.
import { TestBed } from '@angular/core/testing';
import { UserProfileComponent } from './user-profile.component';
describe('UserProfileComponent', () => {
it('runs ngOnInit on the first detectChanges', () => {
const fixture = TestBed.createComponent(UserProfileComponent);
const spy = spyOn(fixture.componentInstance, 'ngOnInit').and.callThrough();
fixture.componentRef.setInput('userId', '7');
expect(spy).not.toHaveBeenCalled();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
});
});Common mistakes
- Reading view queries in
ngOnInit. A@ViewChildresult may beundefinedhere. Move that code tongAfterViewInit. - Forgetting to clean up. A subscription started in
ngOnInitoutlives the component unless you tie it toDestroyRefor unsubscribe inngOnDestroy. - Putting heavy computation in the hook. The first render waits for synchronous work in
ngOnInit. Start asynchronous work and render a loading state instead. - Assuming one call per route. Navigating between two URLs that use the same component can reuse the instance. In that case
ngOnInitdoes not run again, and you need to observe route parameters instead.
Exercise
A parent template renders <app-user-profile [userId]="selectedId" />. The user clicks a button that changes selectedId from '1' to '2'. The component loads data only in ngOnInit. What does the user see, and what is the smallest change that fixes it?
Show answer
The component shows user 1 forever, because ngOnInit runs once per instance and the parent reuses the same instance. The fix is to run the load in ngOnChanges when changes['userId'] is present. Because ngOnChanges also runs before the first ngOnInit, the initial load is covered too. Unsubscribing the previous request avoids an older response overwriting a newer one.
Exercise
Why does takeUntilDestroyed() with no argument fail when called inside ngOnInit, and what do you pass instead?
Show answer
Without an argument, takeUntilDestroyed calls inject(DestroyRef), which only works in an injection context such as a constructor or field initializer. ngOnInit is not one. Inject DestroyRef as a field and pass it explicitly: takeUntilDestroyed(this.destroyRef).