21

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();
}
Phonolog
  • 6,321
  • 3
  • 36
  • 64
Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93
  • 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. – Nyasha Chinyuku Feb 18 '22 at 10:11

5 Answers5

10

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

siva kumar
  • 569
  • 1
  • 3
  • 13
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.

Phonolog
  • 6,321
  • 3
  • 36
  • 64
7

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.

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

Supriya
  • 481
  • 5
  • 5
0

If you use

ngOnInit()

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

ionViewWillEnter()