Sub topic 3
Modern Angular Lifecycle Behavior
Assume you know basic TypeScript, Angular components, and RxJS subscriptions. This chapter focuses on cleanup, hook order, rendering, signals, and testing.
Modern cleanup with `DestroyRef` and `takeUntilDestroyed`
DestroyRef represents the lifetime of the current component. takeUntilDestroyed completes an observable when that component is destroyed.
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
standalone: true,
template: `Ticks: {{ ticks }}`,
})
export class TickerComponent {
private readonly destroyRef = inject(DestroyRef);
ticks = 0;
constructor() {
interval(1000)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => this.ticks++);
}
}This avoids storing a Subscription and writing a separate ngOnDestroy method.
Hook order at a glance
During creation and the first change-detection pass, Angular generally calls hooks in this order:
| Phase | Hooks |
|---|---|
| Inputs and initialization | `ngOnChanges`, `ngOnInit`, `ngDoCheck` |
| Projected content | `ngAfterContentInit`, `ngAfterContentChecked` |
| Component view | `ngAfterViewInit`, `ngAfterViewChecked` |
| Later checks | `ngOnChanges`, `ngDoCheck`, checked hooks |
| Destruction | `ngOnDestroy` |
The exact work performed during a check can vary, but hooks should be cheap because change detection may run often.
Parent and child ordering
A parent can begin its check before Angular checks its child. Child hooks then run while Angular processes the child subtree. Avoid depending on a fragile exact interleaving between parent and child hooks. Use inputs and outputs for communication.
Render hooks
Use afterNextRender for browser-only DOM work after Angular renders:
import { Component, afterNextRender } from '@angular/core';
@Component({
selector: 'app-measure',
standalone: true,
template: `<div>Content</div>`,
})
export class MeasureComponent {
constructor() {
afterNextRender(() => {
console.log('The DOM is rendered');
});
}
}afterRender runs after later render cycles. These callbacks do not run during server-side rendering.
Signals and lifecycle hooks
Signal inputs can replace many ngOnChanges cases. A computed value derives state, while an effect reacts to changes:
import { Component, computed, effect, input } from '@angular/core';
@Component({
selector: 'app-user',
standalone: true,
template: `{{ label() }}`,
})
export class UserComponent {
userId = input.required<string>();
label = computed(() => `User: ${this.userId()}`);
constructor() {
effect(() => console.log('User changed:', this.userId()));
}
}Use hooks for lifecycle boundaries and signals for reactive state.
Common pitfalls
- Do not read a view query before
ngAfterViewInit. - Do not perform expensive work in
ngDoCheckor checked hooks. - Do not mutate bound state during a check without understanding the timing. This can cause
ExpressionChangedAfterItHasBeenChecked. - Always clean up manual subscriptions, timers, and event listeners.
Testing lifecycle behavior with TestBed
fixture.detectChanges() creates the component and runs its initial hooks. fixture.destroy() runs destruction cleanup.
const fixture = TestBed.createComponent(TickerComponent);
fixture.detectChanges();
expect(fixture.componentInstance.ticks).toBe(0);
fixture.destroy();Test cleanup when a resource must stop after destruction.
Exercise
Which tool automatically completes an interval subscription when its component is destroyed?
Show answer
takeUntilDestroyed, connected to the component's DestroyRef.