What is ngOnInit?
When you create a new component, you will realize that a method named ngOnInit ( ) appears below the constructor:
import {Component,OnInit} from ‘@angular/core’;
@Component ({
selector :’app-home’,
templateUrl:’./home.component.html’,
styleUrls:[‘./home.component.css’]
})
export class HomeComponent implements OnInit{
constructor(){}
ngOnInit{
}
}
Every component has a lifecycle. The ngOnInit() method is called immediately after Angular finishes setting up the component.
What we can do inside the ngOnInit() method is that some operations like fetching data, or something we want to see immediately on page load. It is not recommended to do these kinds of operations inside the constructor, so we have ngOnInit instead.
In Angular, the constructor should only be responsible for dependency injection.
we need ngOnInit() method for:
- To perform complex initializations shortly after construction.
- To set up the component after Angular sets the input properties.
An ngOnInit() is a good place for a component to fetch its initial data.