Understanding Angular lifecycle methods with Examples

In Angular, components have a lifecycle managed by Angular itself, from creation to destruction. Angular provides lifecycle methods that you can use to tap into this process and perform custom logic at specific points in the lifecycle.

Here are some examples of how you might use each lifecycle method:

ngOnChanges: This method is called whenever a bound input property changes. You can use it to react to changes in input properties and perform logic when the value of an input property changes.

In this example, the CounterComponent implements the ngOnChanges method and logs the changes to its input properties.

  1. ngOnInit: This method is called after the first ngOnChanges call and is used to perform initialization logic for the component.

In this example, the HelloComponent implements the ngOnInit method and initializes its name property.

  1. ngDoCheck: This method is called during every Angular change detection cycle and is used to perform custom change detection.

In this example, the TodoListComponent implements the ngDoCheck method and logs its items array.

  1. ngAfterContentInit: This method is called after the component’s content has been fully initialized.

In this example, the TabsComponent implements the ngAfterContentInit method and logs a message to the console.

  1. ngAfterContentChecked: This method is called after every change detection cycle that updates the component’s content. It can be used to perform logic that depends on the component’s content being fully updated and checked.

In this example, the TabsComponent implements the ngAfterContentChecked method and logs a message to the console.

6. ngAfterViewInit: This method is called after the component’s view (including its child views) has been fully initialized.

In this example, the TabPanelComponent implements the ngAfterViewInit method and logs a message to the console.

7. ngAfterViewChecked: This method is called after every change detection cycle that updates the component’s view (including its child views).

In this example, the TabListComponent implements the ngAfterViewChecked method and logs a message to the console.

8. ngOnDestroy: This method is called just before the component is destroyed by Angular. It can be used to perform cleanup logic for the component, such as unsubscribing from observables or detaching event handlers.

In this example, the TimerComponent implements the ngOnDestroy method and uses it to stop the interval timer it started in its ngOnInit method.

I hope you found this article useful and informative. Thanks 😊

Leave a Reply