Mohan Gopi Mohan Gopi - 1 year ago 265
TypeScript Question

what is the purpose of ionViewDidLoad() function

On giving

ionic g page pageName
i am getting generated .ts,.css and .html file

inside .ts file i am having a function called
and this is getting printed before my view appears.

this can be done in constructor it self i believe.

can some one give me some reference of any blog or some explanation about this function would really help me

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. Again, 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.

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