Angular FAQ: Top Questions
20. What are lifecycle hooks and how are they useful?
Lifecycle hooks allow Angular to tap into key moments in a component’s lifecycle: creation, update, and destruction. Common hooks include:
ngOnInit()
: Runs once after component is initialized.ngOnChanges()
: Called when input properties change.ngOnDestroy()
: Cleanup logic when component is destroyed.
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Initialized');
}
ngOnDestroy() {
console.log('Destroyed');
}
}