Open In App

What is the Difference between Constructor and ngOnInit in AngularJS ?

Constructor: Constructor is the default method for a class that is created when a class is installed and ensures the proper execution of the roles in the class and its subsections. Angular are preferably the Dependency Injector (DI), analyzes the builder’s components and when creating a new feature by calling the new MyClass() tries to find suppliers that match the builder’s parameter types, resolve them and pass them to similar components.

new MyClass(someArg);

Example:






var AddNumbers= (function () {
    function AddNumbers(x, y) {
        this.x = x;
        this.y = y;
    }
    AddNumbers.prototype.add = function () {
      return this.x + point.x;
    };
    return AddNumbers;
})();
  
  
var numbers = new AddNumbers(2, 4);
var additionOfNumbers = numbers.add();
console.log(additionOfNumbers);

Output:

6

ngOnInit: OnInit is a life cycle widget called Angular to show that Angular is made to create a component. We have to import OnInit like this to use it (actually using OnInit is not mandatory but it is considered good).



Syntax:

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

and to use it to execute the OnInit method, we should use a section like this:

Example:




import { Component, OnInit } from '@angular/core';
  
@Component({
    selector:'app-checkbox',
    templateUrl:'./checkbox.component.html',
    styleUrls: ['./checkbox.component.css']
})
  
export class CheckboxComponent implements OnInit {
    constructor() {
        console.log('Called Constructor');
    }
  
    ngOnInit() {
        console.log('Called ngOnInit method');
    }
}

Output:

Called Constructor
Called ngOnitit method

Note: Class app sales

constructor () {
// First called before ngOnInit ()
}
Oninit () {
// Named after the constructor and named after NgOnChanges()
}

Use this interaction to apply custom startup thinking after the launch of the admin property. NGOnInit is named after the indexing of the target sites for the first time, and before any of its children are tested. Only once a guide is included.

Difference between ngOnInit and Constructor:

Conclusion:


Article Tags :