Sub topic 2
Constructor versus ngOnInit: where initialization belongs
This chapter assumes you can write a basic Angular component with a template. It also assumes you know TypeScript classes, can bind inputs and events in templates, and have used RxJS subscriptions. After reading it you should be able to decide, for any piece of setup code, whether it belongs in the constructor, in a field initializer, or in ngOnInit.
Two different moments in a component's life
A component is a TypeScript class. Angular creates it in two steps that are easy to blur together.
- Instantiation. Angular calls
newon your class, resolving constructor dependencies through dependency injection (DI). The constructor and all field initializers run now. - Binding and initialization. Angular writes the values bound in the parent's template into your inputs. It then calls
ngOnChangesif any bound input is set, and thenngOnInit, once.
The constructor is a feature of the JavaScript language. ngOnInit is a feature of Angular. The constructor runs because the object exists. ngOnInit runs because Angular has finished its first round of input binding and tells you so.
What is not available in the constructor
Inputs are the main example. While the constructor runs, Angular has not yet written any input values. A decorator-based input still holds its initial value, and a required input has none at all.
import { Component, Injectable, Input, OnInit, inject } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class UserService {
load(id: string): Observable<string> {
return of(`User ${id}`);
}
}
@Component({
selector: 'app-user-name',
standalone: true,
template: `<p>{{ name }}</p>`,
})
export class UserNameComponent implements OnInit {
@Input({ required: true }) userId!: string;
name = '';
private readonly users = inject(UserService);
constructor() {
// userId is still undefined here: Angular has not bound it yet.
console.log('constructor', this.userId);
}
ngOnInit(): void {
// userId holds the value from the parent's template.
console.log('ngOnInit', this.userId);
this.users.load(this.userId).subscribe((value) => (this.name = value));
}
}If a parent renders <app-user-name userId="42" />, the first log prints undefined and the second prints 42. Code that needs userId, such as the data request above, therefore belongs in ngOnInit.
Other things are also missing in the constructor:
- The view. The component's template has not been created, so
@ViewChildresults and DOM elements do not exist. Those become available in the AfterView hooks, covered in a later chapter. - Projected content. Content children are not resolved either.
- A settled state. Nothing has been through change detection yet.
What belongs in the constructor
Keep the constructor close to its job: building the object. Good candidates are:
- Receiving dependencies. Modern Angular prefers
inject()in a field initializer, asUserNameComponentdoes above. Constructor parameters work equally well. - Assigning default values and simple state that depends on nothing external.
- Setup that must run in an injection context. Angular lets you call
inject(),effect()andafterNextRender()only while the object is being constructed. That includes field initializers. It does not includengOnInit, which runs later, outside that context.
The last point is a real reason to use the constructor, not just a convention.
import { Component, OnInit, computed, effect, input } from '@angular/core';
@Component({
selector: 'app-greeting',
standalone: true,
template: `<p>{{ label() }}</p>`,
})
export class GreetingComponent implements OnInit {
readonly name = input.required<string>();
readonly label = computed(() => `Hello, ${this.name()}`);
constructor() {
// Registering an effect needs an injection context, so it goes here.
// The effect callback runs later, after inputs are set.
effect(() => console.log('name changed to', this.name()));
// Reading this.name() directly here would throw:
// the required input has no value yet.
}
ngOnInit(): void {
console.log('ngOnInit sees', this.name());
}
}The computed and the effect read this.name() lazily, so they can be declared in the constructor or a field initializer. Reading a required signal input eagerly, outside such a callback, only works once Angular has bound it. ngOnInit is the earliest place for that.
What belongs in ngOnInit
Put work in ngOnInit when it depends on the component's inputs or is a side effect of the component becoming active:
- Requesting data that depends on an input, such as an ID.
- Subscribing to observables, including ones built from inputs.
- Starting timers or registering listeners that you will release in
ngOnDestroy. - Validating that required inputs are consistent with each other.
A useful test is this: could a unit test create the class and reasonably expect nothing to happen yet? Network calls, subscriptions and timers are side effects. Keeping them out of the constructor means that creating the object stays cheap and predictable.
| Task | Constructor or field initializer | ngOnInit |
|---|---|---|
| Inject a service | Yes | No (outside the injection context) |
| Set a default value | Yes | Possible, but unnecessary |
| Read a decorator `@Input` | No, not yet set | Yes |
| Read a signal input directly | No, throws if required | Yes |
| Create `effect()` or `computed()` | Yes | No for `effect()` |
| Start an HTTP request that uses an input | No | Yes |
| Start a subscription or timer | Avoid | Yes |
| Query the DOM or a view child | No | No, wait for AfterView |
Guarantees and edge cases of ngOnInit
- It runs once per instance.
ngOnInitis not called again when inputs change. For ongoing reactions to changes, usengOnChanges(the next chapter) or signal-based reactions. - It runs even with no inputs.
ngOnChangesis skipped when a component has no bound inputs.ngOnInitstill runs, so it is the dependable place for first-time setup. - It runs before the first render of this component's own view. Setting properties here does not trigger an
ExpressionChangedAfterItHasBeenCheckederror, because the template has not been checked yet. - Angular does not wait for async work. Writing
async ngOnInit()compiles, becauseOnInitallows a return value that is ignored. Angular does not await the promise, so the template renders before yourawaitcompletes. Initialize fields to sensible empty values and update them when the data arrives. - Inheritance needs care. If a base class implements
ngOnInit, a subclass that defines its own must callsuper.ngOnInit(). Otherwise the base logic silently never runs. Likewise, a subclass constructor must callsuper()before usingthis.
import { Directive, OnInit } from '@angular/core';
@Directive()
export abstract class BaseWidget implements OnInit {
protected ready = false;
ngOnInit(): void {
this.ready = true;
}
}
export class SpecialWidget extends BaseWidget {
override ngOnInit(): void {
super.ngOnInit(); // without this call, ready stays false
// additional setup for SpecialWidget
}
}Common mistakes
- Reading inputs in the constructor. The value is
undefined(or an error for required signal inputs). Move the logic tongOnInit. - Doing heavy work in the constructor. Angular may create components in situations where they are never initialized, and tests instantiate them constantly. Heavy work there slows everything down and makes tests harder to write.
- Expecting
ngOnInitto rerun. If an input changes after init and you fetch data only inngOnInit, the component shows stale data. Handle later changes explicitly. - Duplicating logic in both places. If the constructor and
ngOnInitboth set the same state, one will overwrite the other, and the order is hard to follow. Choose one.
Exercise
A component has @Input() orderId!: string; and in its constructor calls this.orders.fetch(this.orderId). The request always goes out with undefined. Explain why, and say where the call should move.
Show answer
The constructor runs when Angular instantiates the class, before it writes the bound input values, so orderId is still undefined. Move the call to ngOnInit, which runs after the first input binding. If orderId can change later, also react to those changes with ngOnChanges or a signal-based approach, because ngOnInit runs only once.
Exercise
You want to register effect(() => console.log(this.count())) in a component. Can you do this inside ngOnInit? Where should it go, and why?
Show answer
Not directly. effect() requires an injection context, which exists during construction (the constructor or a field initializer) but not inside ngOnInit. Register it in the constructor or as a field initializer. The effect callback runs later, after inputs are set, so reading this.count() there is safe.
Exercise
A developer writes async ngOnInit() { this.data = await this.api.load(); } and sees the template render once with an empty data before it fills in. Is this a bug in Angular? What should the component do?
Show answer
No. Angular calls ngOnInit and ignores the returned promise, so rendering proceeds before the await finishes. Give data an empty initial value (or a loading flag) and let the template handle that state, then update the field when the promise resolves.