Component Lifecycle

Component Lifecycle

The lifecycle of an Angular component represents a series of events that a component goes through from its creation to its destruction. Each lifecycle event or hook provides an opportunity to perform specific tasks at a specific stage in the component's life.

Understanding the component lifecycle is critical to managing component behaviour, optimizing performance, and avoiding memory leaks. Efficient use of lifecycle hooks enables data initialization, change management, and proper resource cleanup.

Below are the Angular Component Lifecycle Phases:

  1. ngOnChanges - It's executed right at the start when a new component is created. But thereafter, it's also always called, whenever any bound input properties (@input) change.

  2. ngOnInit - It's executed once the component has been initialized but it has not been added to DOM yet. ngOnInit will run after the constructor

  3. ngDoCheck - It will run whenever change detection runs. Change detection is the system by which Angular determines whether something changed on the template of a component, or inside of a component. Whether it needs to change something in the template or some property value change, Angular needs to re-render that part of the template. And ngDoCheck is a hook executed on every check Angular makes.

  4. ngAfterContentInit - It is executed whenever the content displayed by ng-content has been initialized. So not the component view itself, but the main component view, more precisely the part that is added to our component via ng-content.

  5. ngAfterContentChecked - It is executed whenever change detection checked the content we're projecting into our component.

  6. ngAfterViewInit - It is executed after the component’s view (and child views) has been initialized.

  7. ngAfterViewChecked - It is executed every time the view (and child views) have been checked.

  8. ngOnDestroy - It is executed once the component is about to be destroyed.

Did you find this article valuable?

Support Sankarshan Ramesh by becoming a sponsor. Any amount is appreciated!