Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Initialization of components class variables

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

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!