Petros Kyriakou
Petros Kyriakou

Reputation: 5343

When to use a constructor and when to use OnInit

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

Answers (1)

Thierry Templier
Thierry Templier

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 changes
  • ngOnInit 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

Related Questions