Difference between constructor and ngOnInit

The constructor is a default Typescript class method whereas ngOnInit is a lifecycle hook in angular. However, both methods can be used for initialization purposes.

Constructor

The constructor method executes as soon as the object of the class is created. We can use the constructor to initialize the class members. The constructor executes before the ngOnInit method.

We can use the constructor to inject dependency.

export class MyComponent {
  constructor(private service: MyService, private http: HttpClient) {}
}

ngOnInit

This method is invoked after component initialization. We can use this method for initialization and to perform pre-work that is needed when the component is loaded, like initializing reactive forms or getting data from the server and displaying them, etc. This method executes after the first ngOnChanges call.

To use the ngOnInit method, we need to implement the onInit interface present in the @angular/core package.

export class AppComponent implements OnInit {
  constructor() {
     //initialization 
  }

  ngOnInit() {
     // code to execute before component loaded
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *