Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnInit vs ionViewDidLoad in ionic 2 or ionic 2+

Which one will I use for initializing data and why?

ngOnInit() {     this.type = 'category';     this.getData();     this.setData(); }  ionViewDidLoad() {     this.type = 'category';     this.getData();     this.setData(); } 
like image 622
saif Avatar asked Apr 30 '17 05:04

saif


People also ask

What is ngOnInit in Ionic?

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.

How do you use ionViewWillEnter in ionic?

First, about ionic life cycle. If you write down all ionic events and put a console. log in each, you will see the scenario: constructor --> ionViewDidLoad --> ionViewWillEnter --> ionViewDidEnter --> ionViewWillLeave --> ionViewDidLeave --> ionViewWillUnload.

What is Afterviewinit in angular?

ngAfterViewInit()linkA callback method that is invoked immediately after Angular has completed initialization of a component's view. It is invoked only once when the view is instantiated.

What do you mean by ionic lifecycle?

Ionic Lifecycle Methods​Fired when the component routing to has finished animating. ionViewWillLeave. Fired when the component routing from is about to animate. ionViewDidLeave. Fired when the component routing to has finished animating.


2 Answers

ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.

ionViewDidLoad is related to the Ionic's NavController lifeCycle events. It runs when the page has loaded. This event only happens once per page being created.

Basically both are good places for initializing the component's data.

But for using ngOnInit you need to implement the Angular's OnInit class, In the other hand ionViewDidLoad could be only defined for components that are pushed/popped from a NavController.

So I would say use the ionViewDidLoad for components in the NavController stack and ngOnInit for other components.

like image 135
naomi Avatar answered Sep 16 '22 19:09

naomi


ionViewDidLoad firing is close related to the NavController.

If you need a hook for a component that is rendered independent of the NavController (not all components in an ionic 2 app are pages) you should use angular lifecycle hooks instead of ionic navcontroller hooks.

Now, which one is suitable for you, it depends on the implementation case.

Anyway the names of all those hooks are self-explanatory most of the times.

like image 25
orouwk Avatar answered Sep 17 '22 19:09

orouwk