Sub topic 4
Initializing a component with ngOnInit
This chapter assumes you can write a standalone Angular component, bind inputs in a template, and read a basic RxJS subscription. It covers ngOnInit, the hook where most components do their startup work.
What ngOnInit does
ngOnInit is a method Angular calls once, after it has set the component's input properties for the first time. You add it by implementing the OnInit interface.
The hook runs once per component instance. If the component is destroyed and created again, for example by an @if block or a route change, the new instance gets its own call.
A worked example
The component below loads a user from an HTTP endpoint. It needs userId to build the URL, so the request has to wait until the input is set. ngOnInit is the first place where that is guaranteed.
import { Component, Input, OnInit, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface User {
id: string;
name: string;
}
@Component({
selector: 'app-user-profile',
standalone: true,
template: `
@if (user) {
<h2>{{ user.name }}</h2>
} @else {
<p>Loading...</p>
}
`,
})
export class UserProfileComponent implements OnInit {
@Input() userId = '';
private readonly http = inject(HttpClient);
user?: User;
ngOnInit(): void {
this.http
.get<User>(`/api/users/${this.userId}`)
.subscribe((user) => (this.user = user));
}
}The application must register the client with provideHttpClient() for this to run. The inject call in the field initializer is dependency injection, which is fine during construction. The request itself sits in ngOnInit because it reads an input.
Where it fits in the sequence
Angular creates the component with its constructor, sets the inputs, calls ngOnChanges if any bound input is present, and then calls ngOnInit. After that, the first change detection pass renders the template.
If a component has no bound inputs, ngOnChanges is skipped and ngOnInit still runs.
What belongs in ngOnInit
Good candidates:
- Starting data requests that depend on input values.
- Subscribing to observables, paired with cleanup (see the chapters on
ngOnDestroyandDestroyRef). - Computing initial state derived from inputs.
Keep the constructor for dependency injection and simple field setup. Keep the hook short. Slow synchronous work in ngOnInit delays the first render.
Common errors
The most frequent mistake is expecting ngOnInit to run again when an input changes. It does not. In the example, if the parent changes userId from '1' to '2', the profile keeps showing user 1. To react to later changes, use ngOnChanges, which the previous chapter covered.
Other mistakes:
- Reading
@ViewChildresults inngOnInit. The view is not created yet, so the value is usuallyundefined. UsengAfterViewInitinstead. - Forgetting
implements OnInit. Angular still calls the method, but the compiler no longer checks its name and signature, so a typo such asngOnIntfails silently. - Subscribing without unsubscribing. A subscription started in
ngOnInitto a long-lived source keeps running after the component is removed.
Exercise
A parent binds [userId]="id" to UserProfileComponent, and id changes from "1" to "2" while the component stays on screen. Does the component load user 2? If not, which hook would you add?
Show answer
No. ngOnInit ran once, when the component was first set up, so the request for user 1 is the only one made. Add ngOnChanges and check changes['userId'] to load the new user. A signal input with an effect would also work.