Ionic 2 — Refresh components on page enter

Chris Hand
2 min readNov 22, 2017

--

A big thing in Angular is being able to refresh components when certain life-cycle hooks occur. NgOnInit , NgAfterViewInit etc. Ionic capitalizes on those hooks by allowing you to do some really powerful things when a page becomes active in your application. Some of these hooks are ionViewDidEnter and ionViewWillEnter , among others. This is immensely helpful for refreshing data when a user enters a page for the first time or in any subsequent times. When used correctly, you can even get rid of the need to have a pull-down to refresh interaction or something similar.

A common problem I run into is that I’m not working with full pages that fetch data, but individual components. I often wonder, “How can I get this component to know when it’s active, so it can refresh its data?”. It’s not a page, so I can’t use one of the page lifecycle hooks… but there’s got to be some way to do it.

One pattern I’ve seen is to listen to these hooks on a parent page, and then manually call component methods like refresh() to make sure that everything is in sync. Yeah… that works, but it has a bad code smell. Sometimes I want my component to be a little smaller.

Then I found a little thing called the ViewController in Ionic 2. The most common use case for the ViewController in Ionic 2 is to be able to dismiss modals. In fact, before this, I used it almost exclusively for that. Turns out though, this controller is a really powerful tool!

From the Ionic documentation, this component allows you to simply:

Access various features and information about the current view.

Not very verbose, but injecting this into a component allows you to listen to things like:

ngOnInit() {
this.viewCtrl.didEnter.subscribe(() => {
console.log('Component active');
});
}

You can also subscribe to didLeave. And also access things like the content of the page, etc.

Wow! That’s exactly what I need! Now I don’t have to listen on a parent element. I am listening to the parent element right here.

Keep in mind that this really is listening to the containing Page of a component, not to the component itself. This will have some nuances to it, but at least this is a great new avenue to explore.

Enjoy!

--

--

Chris Hand

Helping teams take ownership of their product and empower themselves to do great things.