The ‘ngOnInit‘ lifecycle hook is a method provided by the Angular framework that gets called automatically after a component is created and its properties are initialized. It is primarily used to perform any additional initialization tasks that couldn’t be performed during the construction or property initialization phase.
The purpose of ‘ngOnInit‘ is to separate the initial setup and configuration of a component from the constructor. The constructor is typically used for dependency injection and basic initialization, while the real component’s behavior and data manipulation should take place inside ‘ngOnInit‘.
The main reason behind this separation is that Angular bindings are not available during the constructor execution, whereas, ngOnInit has access to bindings, inputs, and other dependencies, which makes it a safer place to perform additional setup tasks.
For example, when you are fetching data from a service or a remote API, you should use the ‘ngOnInit‘ method instead of the constructor. Here’s an example that demonstrates the usage of the ‘ngOnInit‘ lifecycle hook:
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
template: `
<div *ngFor="let item of data">
{{item.name}}
</div>
`,
})
export class AppComponent implements OnInit {
data: any[];
constructor(private dataService: DataService) {
// The constructor is used for dependency injection and basic initialization.
}
ngOnInit(): void {
// Fetch the data from the service inside ngOnInit.
this.dataService.getData().subscribe((response) => {
this.data = response;
});
}
}
In this example, we have a ‘DataService‘ that fetches data from a remote API. The service is injected into the ‘AppComponent‘ constructor. The component fetches the data and assigns it to the ‘data‘ property in the ‘ngOnInit‘ method.
In conclusion, ‘ngOnInit‘ is a lifecycle hook used to perform additional setup required for a component after it is created and ready to interact with other Angular components, inputs, and services.