Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda