Introduction

Angular is a powerful front-end framework that provides tools to build highly scalable and efficient web applications. While working with Angular, developers come across different lifecycle hooks that provide opportunities to execute methods at specific stages of the component’s life cycle. These hooks allow developers to perform initialization and release tasks related to component instances.

In this article, we will discuss two major lifecycle hooks of Angular, ngOnInit and ngOnDestroy, and explore their specific use cases with code examples.

Angular Lifecycle Hooks

Angular lifecycle hooks are the methods that are invoked at various points in the lifecycle of a component. These hooks provide a way to associate functionality with the component instance at specific intervals. Some lifecycle hooks are:

– ngOnChanges()
– ngOnInit()
– ngDoCheck()
– ngAfterContentInit()
– ngAfterContentChecked()
– ngAfterViewInit()
– ngAfterViewChecked()
– ngOnDestroy()

ngOnInit() Hook

ngOnInit() is one of the most commonly used lifecycle hooks in Angular. This method is invoked once, immediately after the component has been initialized, and its inputs have been bound for the first time. The ngOnInit() method is a good place to perform initialization tasks for the component’s properties, such as setting default values or initializing the component’s state by making API calls or fetching data from a server.

Here’s a code example that demonstrates the usage of ngOnInit() hook:

“`
import { Component, OnInit } from ‘@angular/core’;
import { AuthService } from ‘./services/auth.service’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnInit {
isLoggedIn: boolean;

constructor(private authService: AuthService) {}

ngOnInit(): void {
this.isLoggedIn = this.authService.isLoggedIn();
}
}
“`

In the above example, we have implemented the ngOnInit() hook to set the value of isLoggedIn property by calling a method named isLoggedIn() from AuthService, which returns a boolean value indicating whether a user is authenticated or not.

ngOnDestroy() Hook

ngOnDestroy() is another lifecycle hook provided by Angular. This hook is invoked just before the component is destroyed or removed from the DOM. This method is useful when you want to perform cleanup tasks, such as clearing intervals or subscriptions that are no longer required, or deallocating resources that were allocated during the component’s lifecycle.

Here’s an example of ngOnDestroy() hook:

“`
import { Component, OnDestroy} from ‘@angular/core’;
import { Subscription } from ‘rxjs’;
import { UserService } from ‘./services/user.service’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnDestroy {
user: any;
subscription: Subscription;

constructor(private userService: UserService) {
this.subscription = userService.getUser().subscribe((user) => {
this.user = user;
});
}

ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
“`

In the above code example, we have implemented the ngOnDestroy() hook to clear the subscription when the component is destroyed. Here, we are subscribing to getUser() method from UserService to get user data and storing the subscription in the variable named subscription. When the component gets destroyed, ngOnDestory() hook will be executed and we will unsubscribe to the subscription using the unsubscribe() method.

FAQs

What is the difference between OnInit and constructor?

The constructor method is called when an instance of a component is created, whereas ngOnInit() is called once the component has been initialized and its inputs have been bound for the first time. The constructor method is used for dependency injection and to set initial values for the component’s properties. ngOnInit() is used for initialization tasks that depend on input values or data that are not available at the time of component creation.

When should I use ngOnDestroy() hook?

ngOnDestroy() hook should be used when you want to release and cleanup resources that were allocated during the lifetime of the component. Some common examples include clearing intervals, disposing of subscriptions, or releasing resources that were allocated in the component or in any of its child components.

Can I use ngOnInit() within ngOnChanges()?

Yes, you can use ngOnInit() within ngOnChanges(). However, it is a good practice to avoid such implementations because ngOnInit() is called only once during the component initialization and ngOnChanges() is called every time the input property changes.

What is the significance of the boolean return value of ngOnDestroy()?

The ngOnDestroy() hook does not return any value, and it must be defined with a void return type.

Can I use multiple ngOnInit() hooks in a single component?

No, you cannot use multiple ngOnInit() hooks in a single component. ngOnInit() can only be defined once in a component, and it must be implemented in the class definition of the component.

Conclusion

Angular provides several lifecycle hooks that are useful for performing various initialization and cleanup tasks. Two important lifecycle hooks, ngOnInit() and ngOnDestroy(), are commonly used in Angular applications to initialize component properties and clean up resources before the component is destroyed. By understanding these hooks and their usage, developers can efficiently manage their application’s lifecycle and build high-performing applications with Angular.

Similar Posts