Master Angular Component Lifecycle: Hooks, Order, and Best Practices
This article explains Angular’s component lifecycle, detailing each hook—from ngOnChanges and ngOnInit to ngAfterViewChecked and ngOnDestroy—their execution order, purposes, and how constructors differ, supplemented with diagrams and console output examples to help developers effectively manage component initialization, change detection, and cleanup.
Overview
Each Angular component has a lifecycle from creation, change detection to destruction. Angular exposes lifecycle hook interfaces such as ngOnChanges, ngOnInit, ngDoCheck, etc., allowing developers to interact with components at key moments.
Lifecycle Execution Order
ngOnChanges
Called when input properties change; receives a SimpleChanges object. It runs before ngOnInit if inputs exist.
ngOnInit
Invoked once after the first ngOnChanges, used for component initialization.
ngDoCheck
Runs during change detection to perform custom checks; executed after ngOnChanges and ngOnInit.
ngAfterContentInit
Called once after component content (ng-content) is initialized.
ngAfterContentChecked
Runs after each check of the component’s projected content.
ngAfterViewInit
Invoked once after the component’s view and child views are initialized.
ngAfterViewChecked
Runs after each check of the component’s view.
ngOnDestroy
Called just before the component is destroyed, useful for cleanup such as unsubscribing from observables.
Constructor vs ngOnInit
The constructor is an ES6 class feature called when the class is instantiated, used in Angular primarily for dependency injection. ngOnInit runs after the constructor and is intended for initializing variables and data bindings.
ngOnChanges
When the OnChanges hook is implemented, Angular calls ngOnChanges() whenever an input property changes, providing the SimpleChanges object.
DoCheck
DoCheck executes custom change‑detection logic when component properties or methods change, traversing all variables.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.