What is ngOnInit in Angular?

While creating a new component in angular, you will realize that a method named ngOnInit ( ) appears below the constructor. Every component has a lifecycle. The ngOnInit() method is called immediately after Angular finishes setting up the component.

What is ngOnInit in Angular?

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.

ngOnInit() method can be used for the following things: 

  1. To perform complex initializations shortly after construction.
  2. To set up the component after Angular sets the input properties.
  3.  A ngOnInit() is a good place for a component to fetch its initial data.

Here is the working example of how to use Angular ngOnInit() method

import {Component,OnInit} from ‘@angular/core’;

@Component ({
selector :’app-home’,
styleUrls:[‘./home.component.css’] })
export class HomeComponent implements OnInit{



Leave a Comment