What is the purpose of the ionViewDidLoad() function?

后端 未结 2 460
故里飘歌
故里飘歌 2021-01-01 13:21

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

Inside the .ts file I have a function called ionViewDidLoad(){}

相关标签:
2条回答
  • 2021-01-01 13:24

    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.

    UPDATE:

    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.

    0 讨论(0)
  • 2021-01-01 13:41

    constructor is called before all, once per instantiation of the page, here you can do initialization that does not refer the HTML DOM

    ionViewDidLoad is called when the page DOM has been loaded, before than the page is shown, also a single time per page instantiation, here you can do initialization thet needs the HTML DOM to be ready

    ionViewWillEnter is called just before the page is shown, maybe multiple times if the page goes in background and returns, here you could refresh data if it can be changed in another page

    ionViewDidEnter is the same but called just after the page is shown, maybe multiple times if the page goes in background and returns, for instance you could show an alert just when the page become in front

    0 讨论(0)
提交回复
热议问题