Angular Lifecycle explained

The Angular lifecycle is the sequence of events that occur when Angular creates, updates, and destroys a component or directive. This will perform actions at specific moments in the lifecycle of a component or directive.

The Angular lifecycle consists of eight phases:

  • ngOnChanges(): Called when Angular sets or resets data-bound input properties. It receives a SimpleChanges object of current and previous property values. It is called before ngOnInit() (if the component has bound inputs) and whenever one or more data-bound input properties change.
ngOnChanges(changes: SimpleChanges) {
  // Handle input property changes
}
  • ngOnInit(): Called once, after the first ngOnChanges(). This will initialize your component or directive, such as fetching data from a service or setting up subscriptions.
ngOnInit() {
  // Initialization tasks
}
  • ngDoCheck(): Called every time Angular runs change detection. Use this to implement your own custom change detection logic, such as detecting changes that Angular cannot or does not detect by default. It is called after ngOnInit() and every ngOnChanges().
ngDoCheck() {
// Custom change detection logic
}
  • ngAfterContentInit(): Called once, after Angular projects external content into the component’s view or the directive’s host element. You can use this hook to access the projected content, such as querying for elements using @ContentChild or @ContentChildren.
ngAfterContentInit() {
// Initialization tasks after content has been initialized
}
  • ngAfterContentChecked(): Called after Angular checks the projected content. You can use this hook to respond to changes in the projected content. It is called after ngAfterContentInit() and every ngDoCheck().
ngAfterContentChecked() {
// Tasks to be performed after content has been checked
}
  • ngAfterViewInit(): Called once, after Angular initializes the component’s view or the directive’s host element. You can use this hook to access the view elements, such as querying for elements using @ViewChild or @ViewChildren.
ngAfterViewInit() {
// Initialization tasks after view and child views have been initialized
}
  • ngAfterViewChecked(): Called after Angular checks the component’s view or the directive’s host element. You can use this hook to respond to changes in the view elements. It is called after ngAfterViewInit() and every ngAfterContentChecked().
ngAfterViewChecked() {
// Tasks to be performed after view and child views have been checked
}
  • ngOnDestroy(): Called once, before Angular destroys the component or directive instance. You can use this hook to perform cleanup tasks, such as unsubscribing from observables, detaching event handlers, or freeing resources.
ngOnDestroy() {
// Cleanup tasks before component is destroyed
}