Life Cycle methods - sravanthimendu98/angular GitHub Wiki

https://www.youtube.com/watch?v=0KWQLFI8mFE

Life Cycle Methods:

  1. ngOnChanges
  2. ngOnInit
  3. ngDoCheck
  4. ngAfterContentInit
  5. ngAfterContentChecked
  6. ngAfterViewInit
  7. ngAfterViewChecked
  8. ngOnDestroy

ngOnChanges(): will be called only when a child component receives a value from parent component using @input decorator.

Purpose: Invoked when any data-bound property of a directive changes.

Usage:

Called before ngOnInit and whenever one or more data-bound input properties change. Receives a SimpleChanges object that contains the current and previous property values.

image

ngOnInit

Purpose: Invoked once, after the first ngOnChanges.

Usage:

Perform component initialization, such as fetching data from a service. Called once after the first ngOnChanges.

ngDoCheck(): does fire when the input property is an array/object like customer class etc and will be called every time a change detection system detects a change

usage:

Detect and act upon changes that Angular doesn't detect on its own. Not recommended for most use cases due to performance implications.

image

ngAfterContentInit: This will be executed only once(single time) after the ngDoCheck.

ngAfterContentChecked: This will be executed after the ngDoCheck and ngAfterContentInit, and next time it will be executed after ngOnCheck as the ngAfterContentInit is executed only once at initial loading. and this can be used when contionuous execution after the ngOnCheck.

  1. ngAfterContentChecked

Purpose: Invoked after every check of the content projected into the component.

Usage:

Respond after Angular checks the content projected into the directive/component.

ngAfterViewInit

Purpose: Invoked once after the component's view and child views have been initialized.

Usage:

Perform initialization that depends on the view being fully initialized.

ngAfterViewChecked

Purpose: Invoked after every check of the component's view and child views.

Usage:

Respond after Angular checks the component's views and child views.

ngOnDestroy Purpose: Invoked just before Angular destroys the directive/component.

Usage:

Perform cleanup such as unsubscribing from observables, detaching event handlers, and other cleanup tasks to avoid memory leaks.

Summary of Common Usage

Initialization (ngOnInit): Most frequently used for component setup and data fetching.

**Input Changes (ngOnChanges): **Essential for responding to changes in input properties.

**Cleanup (ngOnDestroy): **Critical for cleaning up resources to prevent memory leaks.

DOM Initialization (ngAfterViewInit): Important for operations that need to interact with the DOM after itโ€™s fully initialized.

Custom Change Detection (ngDoCheck): Less common but useful for specific custom change detection scenarios.