What is the purpose of the ionViewDidLoad() function?

Mohan Gopi picture Mohan Gopi · Oct 5, 2016 · Viewed 23.5k times · Source

On running ionic g page pageName I get generated .ts,.css and .html files.

Inside the .ts file I have a function called ionViewDidLoad(){} and this is getting printed before my view appears.

This can be done in constructor itself I believe?

Can someone give me some reference of any blog or explanation about this function?

Answer

sebaferreras picture sebaferreras · Oct 5, 2016

You're right, a lot of things could be done both in the constructor or in the ionViewDidLoad and the result will be the same...

But the main difference between the constructor and the ionViewDidLoad is that the constructor will be executed only once (when the component gets instantiated) but the ionViewDidLoad method will be executed every time the view is entered (loaded).

For instance, if you want to load data from a remote datasource, if you do it in the constructor, the data will be obtained only once. If that data could change fast enough, a better approach would be to obtain it in the ionViewDidLoad method, to be sure that every time the page is loaded, the latest data is being obtained and shown in the view.

Another important fact about the ionViewDidLoad