Sub topic 2
Constructor versus ngOnInit: where initialization belongs
This chapter assumes you can write a standalone Angular component, bind inputs in a template, and read basic RxJS code. You should also know TypeScript classes and constructors.
Two places to start work
A component class has two natural places for setup code: the constructor and ngOnInit. They run at different moments, and that difference decides where each kind of work belongs.
- The constructor is a TypeScript feature. Angular calls it when it creates the instance.
ngOnInitis a lifecycle hook. Angular calls it once, after it has set the component's inputs for the first time.
What you can rely on in each
Angular cannot set an input before the object exists. So inside the constructor, every @Input still holds its default value. By the time ngOnInit runs, the inputs bound in the parent template hold their first values.
import { Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-user-card',
standalone: true,
template: `<p>User: {{ userId }}</p>`,
})
export class UserCardComponent implements OnChanges, OnInit, OnDestroy {
@Input() userId = '';
constructor() {
console.log('constructor: inputs are not set yet', this.userId);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['userId']) {
const change = changes['userId'];
console.log('ngOnChanges', change.previousValue, '->', change.currentValue, 'first:', change.firstChange);
}
}
ngOnInit(): void {
console.log('ngOnInit: inputs are set', this.userId);
}
ngOnDestroy(): void {
console.log('ngOnDestroy: release resources here');
}
}If a parent renders <app-user-card userId="42" />, the console shows the constructor line with an empty string. Then it shows ngOnChanges going from undefined to 42 with first: true. Last comes the ngOnInit line with 42.
Where each kind of work belongs
| Work | Constructor | ngOnInit |
|---|---|---|
| Receiving injected services | Yes, as parameters or `inject()` | No |
| Setting simple field defaults | Yes | Possible |
| Reading input values | No, they are not set | Yes |
| Starting HTTP calls or subscriptions that depend on inputs | No | Yes |
| Starting timers or listeners | Avoid | Yes, paired with cleanup |
The common rule: keep the constructor for wiring up dependencies and trivial defaults, and put real startup work in ngOnInit.
Why the split matters
There are three practical reasons.
- Inputs. Code that uses an input in the constructor sees the default value, which is a silent bug and not an error.
- Testing. A constructor with side effects runs whenever a test creates the class. A component whose startup lives in
ngOnInitcan be created first and started on demand. - Predictability.
ngOnInitruns once, at a known point, after Angular has done its binding work.
A common mistake
This version loads data in the constructor and never sees the input:
import { Component, Input, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-user-loader',
standalone: true,
template: `<p>{{ name }}</p>`,
})
export class UserLoaderComponent {
@Input() userId = '';
name = '';
private readonly http = inject(HttpClient);
constructor() {
// Bug: this.userId is still '' here.
this.http.get<{ name: string }>(`/api/users/${this.userId}`)
.subscribe(user => (this.name = user.name));
}
}Moving the request into ngOnInit fixes it. If userId can change later, ngOnChanges is the better place, which the next chapter covers.
Exercise
A component has @Input() orderId = '' and needs to fetch the order once when it appears. Why does a fetch in the constructor request the wrong order, and where should the call go?
Show answer
When the constructor runs, Angular has not yet set the inputs, so orderId is still its default value ''. Put the fetch in ngOnInit, which Angular calls once after the first input values are set.