Ionic 4 : ngOnInit vs ionViewWillEnter
Asked Answered
O

5

22

Which is better to use Angular Lifecycle Hook or Ionic Lifecycle hooks specially for initialization when creating a hybrid app using Ionic 4?

Angular lifecycle hook - ngOnInit

ngOnInit() {
    this.getData();
}

Ionic lifecycle hook - ionViewWillEnter

ionViewWillEnter() {
    this.getData();
}
Often answered 21/1, 2019 at 17:56 Comment(1)
I'm working on an Ionic4 app that shows WordPress posts ionViewWillEnter() actually helped my app to fetch most recent posts each time i load the page as compared to ngOnInit() which kept loading old data from cache.Viviyan
P
11

ionViewWillEnter — Fired when entering a page (also if it’s come back from stack)

ngOnInit will not be triggered, if you come back to a page after putting it into a stack

i think better once ionviewwillenter

Pentateuch answered 1/3, 2019 at 18:40 Comment(0)
C
9

The Ionic 4 migration guide puts it this way:

With V4, we're now able to utilize the typical events provided by Angular. But for certain cases, you might want to have access to the events fired when a component has finished animating during it's route change. In this case, the ionViewWillEnter, ionViewDidEnter, ionViewWillLeave, and ionViewDidLeave have been ported over from V3. Use these events to coordinate actions with Ionic's own animations system.

So the bottom line is to prefer Angular lifecycle hooks like ngOnInit if possible. The only real exception is dealing with Ionics animation system like checking if a component has finished it's entering animation.

Comedic answered 21/1, 2019 at 18:48 Comment(1)
They must have later reversed this? I use "@ionic/angular": "^6.3.2". constructor and ngOnInit are called irregular. I use them to load initial data. I have to use ionViewWillEnter instead. Pretty annoying.Starshaped
E
6

In Ionic 4 Life cycle events are same as angular life cycle events. Ionic 3 Life cycle events not worked here.

For Initialization you must use

ngOnInit()

If you want after view initialized,

Please change

ionviewwillenter

to

ngAfterViewInit()

This will works Fine.

Escaut answered 4/4, 2019 at 8:14 Comment(0)
J
0

ngOnInit

Fired once during component initialization. This event can be used to initialize local members and make calls into services that only need to be done once.

ionViewWillEnter

Jueta answered 5/12, 2019 at 6:8 Comment(0)
P
0

If you use

ngOnInit()

then API data not load properly and values not updated so i strongly recommend

ionViewWillEnter()

Prettypretty answered 21/5, 2021 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.