Performance: Lifecycle execution order mental model
This concept affects how quickly Angular components initialize and update, impacting the time to interactive and smooth user experience.
ngOnInit() {
this.scheduleHeavyTask(); // defer heavy work
}
scheduleHeavyTask() {
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
// heavy computation deferred
});
} else {
setTimeout(() => {
// heavy computation deferred
}, 0);
}
}ngOnInit() {
for(let i = 0; i < 1000000; i++) {
// heavy computation
}
}
ngAfterViewInit() {
// more heavy DOM manipulation
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy logic in ngOnInit | Minimal DOM | 0 | Low | [X] Bad |
| Heavy logic deferred outside lifecycle hooks | Minimal DOM | 0 | Low | [OK] Good |
| Multiple DOM updates in ngOnChanges and ngAfterViewChecked | Multiple DOM updates | 2+ | High | [X] Bad |
| Batched DOM updates with requestAnimationFrame | Single DOM update | 1 | Medium | [OK] Good |
ngOnInit, ngOnChanges, ngAfterViewInit, or ngOnDestroy?ngOnChanges first to react to those changes.ngOnInit runs only once after the first ngOnChanges, so it is not first.ngOnDestroy lifecycle hook in an Angular component?ngOnDestroy is correct.ngOnDestroy required by Angular.export class MyComponent implements OnInit, OnChanges {
@Input() data: string;
ngOnChanges() { console.log('Changes detected'); }
ngOnInit() { console.log('Init called'); }
}ngOnChanges before ngOnInit.ngOnChanges method logs 'Changes detected' first, then ngOnInit logs 'Init called'.ngOnDestroy method is not called when navigating away. What is the most likely cause?ngOnDestroy runs when Angular destroys the component instance.ngOnDestroy won't run.ngOnChanges() { console.log('Changes'); }
ngOnInit() { console.log('Init'); }
ngAfterViewInit() { console.log('After View'); }
ngOnDestroy() { console.log('Destroy'); }ngOnChanges, then ngOnInit runs once, then ngAfterViewInit after view setup.ngOnChanges again. Finally, when component is removed, ngOnDestroy runs.Pass the test and this pattern moves unknown