A lifecycle hook is a function or an event handler that is triggered while navigating between views. This comes in handy in several aspects of the application. Our views don’t get removed while we navigate; they simply get cached. So such lifecycle hooks come in handy. You can read more about them here.

Ionic 2 has 7 hooks namely

onPageLoaded – Similar to ngOnInit

onPageWillEnter – Before view becomes active

onPageDidEnter – After view becomes active

onPageWillLeave – Before view loses focus

onPageDidLeave – After view loses focus

onPageWillUnload – Before page is removed from the DOM.

onPageDidUnload – After page is removed from the DOM.

Now these lifecycle hooks come along with NavController in Ionic 2. To understand them better let’s use a couple of these to build a Realtime Chat application with sockets.io

As I mentioned before, this application is a sequel to my previous post on building a chat application.

First, lets clone the frontend and backend repos using the below commands.

1

2

git clonehttps://github.com/rajayogan/ionic2chat-client.git

git clonehttps://github.com/rajayogan/ionic2chat-server.git

First let’s work with the client.

Navigate to the folder where you have cloned our app and generate two pages using the below command.

1

2

ionic generate page firstroom

ionic generate page secondroom

Now open home.html and move the code to firstroom.html. Similarly open home.js and move the code to firstroom.js