Reputation: 5343
So i have been reading in angular 2 that there are two ways to do the same thing but i do not know its fundamental difference if there is any.
Consider the following
Constructor
export class MyComponent {
myAge: number;
constructor(){
this.myAge = 24;
}
}
OnInit
export class MyComponent implements OnInit{
myAge: number;
ngOnInit(): any {
this.myAge = 24;
}
}
Upvotes: 4
Views: 749
Reputation: 202216
The first one is related to the class instantiation and has nothing to do with Angular2. I mean a constructor can be used on any class. You can put in it some initialization processing for the newly created instance.
The second one corresponds to a lifecycle hook of Angular2 components:
ngOnChanges
is called when an input or output binding value changesngOnInit
is called after the first ngOnChanges
So I would use ngOnInit
if initialization processing relies on bindings of the component (for example component parameters defined with @Input
), otherwise the constructor would be enough...
In your case using the constructor is enough.
Upvotes: 5