Welcome to the Angular tutorial where we will dive into the life cycle hooks OnInit and OnDestroy. These hooks are crucial for managing the lifecycle of your Angular components. Let's get started! šÆ
In Angular, a component's lifecycle has several stages. OnInit and OnDestroy are two essential hooks that help us perform actions at these specific stages.
OnInit: This hook is called after the component's properties are initialized and after the view is initialized. You can use this hook to initialize any data or set up any subscriptions.
OnDestroy: This hook is called just before the component is destroyed. You can use this hook to clean up any resources that the component might have acquired during its lifetime, such as HTTP requests or subscriptions.
Let's create a simple component to demonstrate the usage of OnInit and OnDestroy.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<h1>Welcome to {{ title }}</h1>
`
})
export class ExampleComponent implements OnInit, OnDestroy {
title = 'My Example Component';
subscription: any;
constructor() { }
ngOnInit(): void {
// Initialize data or subscriptions here
this.subscription = setInterval(() => {
console.log(this.title);
}, 1000);
}
ngOnDestroy(): void {
// Clean up resources here
clearInterval(this.subscription);
}
}In the above example, we have a simple component called ExampleComponent. In the ngOnInit hook, we initialize a subscription to a setInterval that logs the title every second. In the ngOnDestroy hook, we clear the subscription to prevent memory leaks.
š” Remember, Angular automatically injects the OnInit and OnDestroy interfaces, so you don't need to import them manually.
What is the purpose of the `OnInit` hook in Angular?
In this tutorial, we learned about the OnInit and OnDestroy hooks in Angular. We created a simple component to demonstrate their usage and discussed their significance in managing the lifecycle of your Angular components.
Stay tuned for more Angular tutorials! š
Happy coding! š