Mohan Gopi Mohan Gopi -4 years ago 184
TypeScript Question

What is the purpose of the ionViewDidLoad() function?

On running

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

Inside the .ts file I have a function called
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 Source

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 is that sometimes you want to interact with the DOM (maybe to initialize a map).

In that case, if you try to access the DOM in the constructor, you will notice that the DOM is not ready by that point and you won't be able to get the map element. The correct approach to do it would be inside the ionViewDidLoad because at that point (just like the name says) the view was already loaded and the DOM is now available.


Just like @graphefruit pointed out in the comment below, in the newest versions of Ionic 2, ionViewDidLoad just fires if the page is not cached. ionViewWillEnter or ionViewDidEnter will be fired every time the page is entered.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download