Member-only story

Difference between Constructor and ngOnInit in Angular.

Ankit Maheshwari
3 min readDec 26, 2019

--

My articles are open for everyone; non-member readers can read the article by clicking this link.

Learn Angular-In-Depth | Learn TypeScript-In-Depth.
इस लेख को हिंदी में पढ़ने के लिए यहां क्लिक करें

Constructor

  • The Constructor is a default method of the class that is executed when the class is instantiated.
  • Constructor ensures proper initialization of fields (class members) in the class and its subclasses.
  • Angular Dependency Injector (DI) analyse the constructor parameters.
  • When we call new MyClass() it creates a new instance of the class.
  • While calling new MyClass() we must have to pass the exact match of the parameters type to the constructor of the class, example:
    new MyClass(arg1:number, arg2:string, argN:any)
  • These arg1:number, arg2:string, argN:any, must be of same type defined in constructor of class MyClass.

ngOnInit

--

--

Ankit Maheshwari
Ankit Maheshwari

Responses (7)