This translation from: Difference and ngOnInit the BETWEEN Constructor
Hook the Provides Life Cycle Angular ngOnInit
by default. Angular provided by default lifecycle hooks ngOnInit
.
Should Why ngOnInit
BE Used, IF WE already have have A constructor
? If we have constructor
, why use ngOnInit
it?
#1st Floor
Reference: The difference between the constructor and ngOnInit https://stackoom.com/question/2Q3mM/
#2nd Floor
Of The Constructor
IS A Method of The default class that IS Executed of Fields. When instantiated and Ensures The class IS PROPER Initialization The class and in subclasses ITS Constructor
is the default method of the class, the method is performed when the class is instantiated and to ensure that the class and correct initialization of the fields in the subclass. Better the Dependency Injector or the Angular (the DI) analyzes and Parameters The constructor When IT A Creates new new instance by Calling new MyClass()
IT tries Set to Find that match Providers The types of Parameters The constructor, and passes Resolves Them to Them The constructor like angle dependence or better injector (DI) analysis constructor parameters, and by calling new MyClass()
attempts to find matches with the type of constructor parameters when creating a new instance of the provider, which is parsed and passed to the constructor, e.g.
new MyClass(someArg);
ngOnInit
is a life cycle hook called by Angular2 to indicate that Angular is done creating the component. ngOnInit
is ngOnInit
called the life cycle linked to indicate Angular create components has been completed.
Have have to Import WE OnInit
in the Order like to use the this (Actually implementingLearn OnInit
IS not mandatory But Considered Good Practice): We must be imported OnInit
in order to use this (in fact, enforcement OnInit
is not mandatory but is considered good practice):
import {Component, OnInit} from '@angular/core';
to use at The Method, of the then OnInit
WE have have to Implement. in at The class like the this and then to use OnInit
the method, we must achieve in this class.
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. Data binding property after the initialization command, implements this interface to perform custom logic initialization. After IS Called The right ngOnInit apos Data-Directive Properties have have been bound for the checked The First Time, and before the any of the checked ITS Children have have been. ngOnInit binding properties after the data and the first check instruction immediately before checking its children transfer. It is invoked only once when the directive is instantiated. After instantiation instructions, called only once.
WE use Mostly ngOnInit
for the Initialization at The All / declaration and Stuff to Avoid Work at The constructor in. In general, we will ngOnInit
be used for all initialization / declaration, and to avoid work in the constructor. The constructor should only be used to initialize class members but should not do actual "work". The constructor should only be used to initialize class members and should not do the actual "work."
Should you use SO constructor()
to Setup Dependency Injection and not much the else. Therefore, you should use constructor()
to set dependency injection, without undue settings. ngOnInit () IS Better Place to "Start" - apos WHERE IT / Components When 'Bindings are resolved. ngOnInit () is the "start" position better - parsing component binding position / positions.
For more information refer here: For more information, see here:
https://angular.io/api/core/OnInit https://angular.io/api/core/OnInit
2 the Component Vs of the OnInit the Constructor the Angular the Angular assembly 2 and constructors OnInit
#3rd floor
Short and simple answer would be, simple and easy answer is that
Constructor
: constructor
IS A default method
the runs ( by deafult ) When Component IS being Constructed. Constructor
: constructor
A default method
run ( the deafult) when the assembly is constructed. The Create you the when an instance
of class A that Time Also constructor(default method)
Would BE Called. Create a class an instance
, the call will be constructor(default method)
. OTHER words in SO, IS being the when the Component constructed or/and an instance is created constructor(default method)
IS Called and Called Relevant code written the WITHIN IS. So in other words, the constructed or/and an instance is created constructor(default method)
component constructed or/and an instance is created constructor(default method)
will call the constructed or/and an instance is created constructor(default method)
relevant code and call one written. And GeneRally in Basically Angular2
IT Used to Inject Things like services
When Component The IS being Constructed Further for use. Basically, typically Angular2
injection, when the assembly is configured for further use, it is usually used for services
something.
OnInit
: NgOnInit IS the Component Life Cycle Hook's First Which runs the After constructor(default method)
the when the Component IS being initialized. OnInit
: NgOnInit is the life cycle of components linked to at initialization component, it is first constructor(default method)
run after.
So, Your constructor will be called first and Oninit will be called later after constructor method. Therefore, the first call the constructor, then call Oninit after the constructor method.
boot.ts boot program
import {Cmomponent, OnInit} from 'angular2/core';
import {ExternalService} from '../externalService';
export class app implements OnInit{
constructor(myService:ExternalService)
{
this.myService=myService;
}
ngOnInit(){
// this.myService.someMethod()
}
}
Resources: LifeCycle Hook resources: LifeCycle Hook
CAN the Check the this by You Small Demo Which Shows Implementation of both-Things. You can view this demo sample of which demonstrates the realization of both.
#4th floor
I think the best example would be using services. I think the best example is the use of the service. Let's say that I want to grab data from my server when my component gets 'Activated'. Acquires data from the server is assumed that I is to be "active" in my assembly. Let's say that I also want to do some additional things to the data after I get it from the server, maybe I get an error and want to log it differently. Let's say I want after obtaining data from the server to the data to do some other things Maybe I encountered an error and want to record it in a different way.
It is really easy with ngOnInit over a constructor, it also limits how many callback layers I need to add to my application. Use ngOnInit really easy on the constructor, it also limits the number of layers I need to add to the callback application .
For Example: For example:
export class Users implements OnInit{
user_list: Array<any>;
constructor(private _userService: UserService){
};
ngOnInit(){
this.getUsers();
};
getUsers(){
this._userService.getUsersFromService().subscribe(users => this.user_list = users);
};
}
with my constructor I could just call my _userService and populate my user_list, but maybe I want to do some extra things with it. I use my constructor, I can only call _userService and filled user_list, but maybe I want to use it to do some something extra. Like make sure everything is upper_case, I am not entirely sure how my data is coming through. Just make sure everything is the same capital, I'm not entirely sure how my data is transmitted.
So it makes it much easier to use ngOnInit. Therefore, it makes it easier to use ngOnInit.
export class Users implements OnInit{
user_list: Array<any>;
constructor(private _userService: UserService){
};
ngOnInit(){
this.getUsers();
};
getUsers(){
this._userService.getUsersFromService().subscribe(users => this.user_list = users);
this.user_list.toUpperCase();
};
}
It makes it much easier to see, and so I just call my function within my component when I initialize instead of having to dig for it somewhere else. It makes viewing much easier, so I call a function in an assembly at initialization, without having to dig elsewhere. Really it's just another tool you can use to make it easier to read and use in the future. Indeed, it is just that you can use another tool to make it easier to read and use in the future. Also I find it really bad practice to put function calls within a constructor! Also, I found the function call in the constructor it is a bad idea!
#5th Floor
The first one (constructor) is related to the class instantiation and has nothing to do with Angular2. The first (constructor) and associated class is instantiated with Angular2 independent. I mean a constructor can be used on any class. I mean, the constructor can be used on any class. You can put in it some initialization processing for the newly created instance. You can do some initial processing of the newly created instance.
The second one corresponds to a lifecycle hook of Angular2 components: The second component corresponds to the life cycle Angular2 hook:
Quoted from official angular's website: references from Angular official website:
ngOnChanges
is called when an input or output binding value changes when an input or output bound value changes, will be calledngOnChanges
ngOnInit
It is called after the firstngOnChanges
ngOnInit
was after the first callngOnChanges
Should you use SO ngOnInit
IF ON Relies Initialization Processing The Bindings of Component (Component Parameters for Example with defined @Input
), otherwise The constructor Would BE enough ... So, you should use ngOnInit
if the initialization process depends on the components (elements is used to define the parameters tied e.g. set @Input
), otherwise the structure is enough ......
#6th floor
The Test the this the To, the I wrote the this code, Borrowing from at The NativeScript the Tutorial : To test this, I wrote the following code draws NativeScript tutorial :
user.ts Username
export class User {
email: string;
password: string;
lastLogin: Date;
constructor(msg:string) {
this.email = "";
this.password = "";
this.lastLogin = new Date();
console.log("*** User class constructor " + msg + " ***");
}
Login() {
}
}
login.component.ts login.component.ts
import {Component} from "@angular/core";
import {User} from "./../../shared/user/user"
@Component({
selector: "login-component",
templateUrl: "pages/login/login.html",
styleUrls: ["pages/login/login-common.css", "pages/login/login.css"]
})
export class LoginComponent {
user: User = new User("property"); // ONE
isLoggingIn:boolean;
constructor() {
this.user = new User("constructor"); // TWO
console.log("*** Login Component Constructor ***");
}
ngOnInit() {
this.user = new User("ngOnInit"); // THREE
this.user.Login();
this.isLoggingIn = true;
console.log("*** Login Component ngOnInit ***");
}
submit() {
alert("You’re using: " + this.user.email + " " + this.user.lastLogin);
}
toggleDisplay() {
this.isLoggingIn = !this.isLoggingIn;
}
}
Console output Console output
JS: *** User class constructor property ***
JS: *** User class constructor constructor ***
JS: *** Login Component Constructor ***
JS: *** User class constructor ngOnInit ***
JS: *** Login Component ngOnInit ***