0

This the code that is used to load a variable with data on the page, using ngOnInit method:

ngOnInit

However, I notice that even if we don't import the OnInit (line 1) and don't write implements OnInit (line 10), the method is still invoked. What is the best practice?

veben
  • 19,637
  • 14
  • 60
  • 80
variable
  • 8,262
  • 9
  • 95
  • 215
  • 1
    [Please don't post your code as an image](//meta.stackoverflow.com/q/285551). It's hard to read, prevents text-based searching, and lowers the overall presentation value of the post. – Suraj Rao Dec 14 '18 at 10:50
  • @veben the method works even if we don't import and implement. It is sufficient that we write ngOnInit(){...do something...} and this works. Hence the question. – variable Dec 14 '18 at 11:42
  • @veben thats.. not true. You can use without it – Suraj Rao Dec 14 '18 at 13:32
  • here https://angular.io/guide/lifecycle-hooks#interfaces-are-optional-technically – Suraj Rao Dec 14 '18 at 13:34

1 Answers1

3

First of all, if you are using Ionic, I would suggest checking ionic lifecycle events. More information can be found here.

To answer your question, if you want to use OnInit, you should import the OnInit and add implements OnInit to the class declaration (as you have already done). If you fail to do so, the Typescript type checks would give you an error message (since this is typescript). It's a good practice thing, and validators won't shout about invalid code.

If you don't want to add implements OnInit, you could use event ionViewDidLoad or any other that would fit best for your need.

So to summarize regarding the best practice:

  • Use one of the Ionic events, if you are developing Ionic app and creating a page.
  • Use ngOnInit and do implements OnInit next to class declaration if you are developing an Angular app OR if you need to do something on initialization of a component within Ionic.
Patiss
  • 187
  • 3
  • 13
  • You can use ngOninit without implementing the interface(it is good practice to implement them). And you can use angular lifecycle hooks in ionic as well. for eg: https://stackoverflow.com/questions/43703271/ngoninit-vs-ionviewdidload-in-ionic-2/43703490 – Suraj Rao Dec 14 '18 at 13:36
  • @SurajRao Sure you can! That is what I wrote, that you can use ngOnInit, but it is not the best practice to use it without implements OnInit statement. Regarding the ionViewDidLoad, since author is asking it for a component that is loading a page, then I provided a suggestion to use ionViewDidLoad instead of ngOnInit. – Patiss Dec 14 '18 at 14:00
  • Your answer seems to suggest not to use angular hooks in Ionic which isnt necessarily true. Otherwise I dont see anything wrong – Suraj Rao Dec 14 '18 at 14:07