I'm starting out in angular2, and I'm wondering about this code
export class HeroesComponent implements OnInit {
// Version 1
myHero: Hero = new Hero('Superman', 'Clark Kent');
// Version 2, 3
// myHero: Hero;
constructor() {
// Version 2
// this.myHero = new Hero('Superman', 'Clark Kent');
}
ngOnInit() {
// Version 3
// this.myHero = new Hero('Superman', 'Clark Kent');
}
}
Right now I've got myHero initialized at the top, but I'm wondering, what goes at the top, what should be inside the constructor and what goes inside ngOnInit?
Because as far as I know, if it's at the top, it's executed straight away, same with the constructor, and ngOnInit?
So what's the difference, and what's correct?
Thank you
Assigning the values in declaration and in the constructor is exactly the same, in fact the compiled version of this:
class HeroesComponent implements OnInit {
myHero: Hero = new Hero('Superman', 'Clark Kent');
}
Is:
var HeroesComponent = (function () {
function HeroesComponent() {
this.myHero = new Hero('Superman', 'Clark Kent');
}
return HeroesComponent;
}());
As for that vs. ngOnInit
, it depends whether or not the constructor of Hero
depends on anything that might not be ready before ngOnInit
is fired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With