OnInit in Angular
OnInit
is a lifecycle hook in Angular that is called after Angular has initialized all data-bound properties of a directive or component. It's a great place to perform initialization tasks that need to happen after the component is created.
When you create a component in Angular, it goes through a series of lifecycle events. OnInit
is one of these events. It's triggered after Angular has finished setting up the component's input properties.
Why Use OnInit?
OnInit
is commonly used for:
- Fetching data from a server.
- Setting up subscriptions to observables.
- Initializing component properties.
- Performing any setup that requires input properties to be available.
Implementing OnInit
To use OnInit
, you need to import the OnInit
interface from @angular/core
and implement the ngOnInit()
method.
Example 1: Fetching Data
In this example, we'll fetch data from a service when the component initializes.
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-data-component',
template: `
<ul>
<li *ngFor="let item of data">{{ item }}</li>
</ul>
`
})
export class DataComponent implements OnInit {
data: string[];
constructor(private dataService: DataService) {}
ngOnInit() {
this.data = this.dataService.getData();
}
}
Explanation:
implements OnInit
: Tells Angular that this component implements theOnInit
interface.ngOnInit()
: Called after Angular initializes the component. We fetch data from theDataService
here.
Example 2: Initializing Properties
In this example, we'll initialize some component properties when the component initializes.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-init-component',
template: '<p>Message: {{ message }}</p><p>Count: {{ count }}</p>'
})
export class InitComponent implements OnInit {
message: string;
count: number;
ngOnInit() {
this.message = 'Component initialized!';
this.count = 0;
}
}
Explanation:
ngOnInit()
: Called after Angular initializes the component. We set the initial values ofmessage
andcount
here.
Key Points
OnInit
is called after Angular initializes data-bound properties.- Use it for initialization tasks that require input properties to be available.
- Always unsubscribe from observables in
ngOnDestroy()
to prevent memory leaks.
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.