Angular Component Lifecycle — ngOnInit and ngOnDestroy 🧐
Drawing from past experience working with various programming language, when learning a new language, it becomes essential to pay close attention to an instance lifecycle to avoid potential memory leak.
As an Angular developer, two of the most crucial lifecycle hooks are ngOnInit and ngOnDestroy. These are concepts that newcomers to Angular often prioritize understanding when they begin exploring the Angular world. To be honest, ngOnInit and ngOnDestroy are not that much of challenge to understand.
Let’s continue reading the article to gain a brief understanding of ngOnInit and ngOnDestroy.
ngOnInit
Based on its name, it appears that ngOnInit signifies that Angular is in its initial state. ngOnInit is only called once after the constructor has been invoked, and all data-bond properties are already initialized. In this lifecycle hook, we can set variables or call services to ensure that the variables are rendered with data.
class MyComponent implements OnInit {
title: string = null;
ngOnInit(){
this.title = "Example";
this.dataService.getData().subscribe();
}
}
ngOnDestroy
Based on its name, ngOnDestroy appears to indicate that Angular is in the process of destroying the component. In ngOnDestroy, we typically include cleanup logic. These codes are executed just before the component gets destroyed. Thus, it is a suitable location to free the resource to prevent memory leaks. We can unsubscribe from observables or unregister all callback functions here.
class MyComponent implements OnInit, OnDestroy {
subscription: Subscription;
ngOnInit(){
this.subscription = this.dataService.getData().subscribe();
}
ngOnDestroy(){
this.subscription.unsubscribe();
}
}
Conclusion
Lifecycle hooks are essential in Angular application, particularly for large scale applications. While the concept of these lifecycle hooks are straightforward, the key is to focus on implementing best practices with these concepts to enhance the effectiveness and maintainability of the application.