Sub topic 1
Angular Component Lifecycle Hooks
Prerequisites
Assume you know basic TypeScript classes, Angular components, property binding, and RxJS subscriptions. A lifecycle hook is a method Angular calls at a specific stage in a component's life.
A component's lifecycle has three broad phases:
- Creation: Angular constructs the class and initializes its inputs.
- Change detection: Angular checks bindings and may call update hooks.
- Destruction: Angular removes the component and gives it a chance to release resources.
The first important order is:
Constructor versus ngOnInit
The constructor is a TypeScript and JavaScript feature. Angular calls it when it creates the class instance. Use it for simple dependency injection and field initialization.
Do not depend on @Input() values in the constructor. Angular sets those values after construction. Use ngOnInit for initialization that needs the initial inputs, such as loading data based on an input.
import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-user-card',
standalone: true,
template: `<p>User: {{ userId }}</p>`,
})
export class UserCardComponent implements OnChanges, OnInit {
@Input() userId = '';
constructor() {
console.log('constructor:', this.userId); // Usually empty
}
ngOnChanges(changes: SimpleChanges): void {
const change = changes['userId'];
if (change) {
console.log('input changed:', change.currentValue);
}
}
ngOnInit(): void {
console.log('initial input:', this.userId);
}
}Reacting to Input Changes with ngOnChanges
ngOnChanges runs when Angular assigns a new value to an input. It receives a SimpleChanges object. Each changed input has a record containing:
previousValuecurrentValuefirstChange
The first call happens before ngOnInit. Later calls happen when the parent supplies a different input value.
Initializing a Component with ngOnInit
ngOnInit runs once, after Angular has assigned the initial inputs. Put one-time setup here. Keep input-dependent initialization here when it does not need to repeat for later input changes. Use ngOnChanges when the setup must react repeatedly.
Exercise
Which hook should load a profile using an initial userId input, and which hook should respond when userId changes later?
Show answer
Use ngOnInit for the one-time initial load. Use ngOnChanges for later input changes.