What is the correct order in which Angular calls the main lifecycle hooks during a component's life?
Short answer
Angular calls them in a predictable sequence: ngOnChanges first if there are any inputs, then ngOnInit once, followed by ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, and ngAfterViewChecked, with ngOnChanges, ngDoCheck, and the checked hooks all…
Advertisement
AModel answer
Angular calls them in a predictable sequence: ngOnChanges first if there are any inputs, then ngOnInit once, followed by ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, and ngAfterViewChecked, with ngOnChanges, ngDoCheck, and the checked hooks all potentially running again on subsequent updates, and ngOnDestroy running once at the very end.
ngOnChanges() { console.log('1. Inputs changed'); }
ngOnInit() { console.log('2. Component initialized'); }
ngAfterViewInit() { console.log('3. View fully initialized'); }
ngOnDestroy() { console.log('4. Component about to be destroyed'); }Real-world example
A developer debugging why a child element referenced with ViewChild was undefined discovers it is only available starting in ngAfterViewInit, not in the earlier ngOnInit, since the view has not fully rendered yet at that point.
Likely follow-ups
- Why is ViewChild data only reliably available starting in ngAfterViewInit?
- What is the practical difference between ngAfterContentInit and ngAfterViewInit?
Related topics