What is the difference between constructor and ngOnlnit in Angular js?

Member

by dejon , in category: Technology , 3 years ago

What is the difference between constructor and ngOnlnit in Angular js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adolf , 3 years ago

The comprehensive comparison that taps into components initialization process is given below:-

  1. ngonInit is just a method in a class which structurally is not different to any other method in a class. Whereas, a constructor is a completely different thing. It will be called when an instance of a class is created.
  2. A class constructor in angular is used to inject dependencies, which is called constructor injection pattern. Whereas, when ngOnInit is called, it has finished creating a component DOM, injected all required dependencies through constructor and processed input bindings.
  3. A constructor is a default method of the class that is executed when the class is instantiated. Whereas, ngOnInit is a life cycle hook called by Angular 2 to indicate that angular is done creating the component.
  4. ngOnInit relies on the binding of the component. Whereas, it is not the case when a constructor is used.