/ ionic

Ionic 3 - Events

Have you ever wanted to communicate across two components when a particular event happens within your application? You can do this by using the Events service within Ionic 3. This article will detail how to use Events and I’ll use an example of making a toast appear when an event is triggered.

The best part is, you do not have to install any third party plugins or libraries, it comes out of the box with Ionic! :)

Here's an older video of this article.

Event Lifecycle

I’ve created the following diagram to explain the lifecycle of an Event with Ionic 3. We can publish a new event, named user:login that we call whenever a user logs into the application.

Ionic 3 Events

A Sample Application

To demonstrate the use of Events, let’s create a simple application that uses events to greet a user. This will consist of two components, a HomeComponent that publishes the event, and a HelloComponent that subscribes to the event and displays a toast when the event fires.

It can have event data parameters such as { user: 'Paul Halliday' } which we can then capture within our subscribe block inside the component that we want to use the event in.

Create a New Ionic Project

I'll be creating a new project for this demonstration:


# New project based on the 'blank' template
$ ionic start Events blank

# Navigate to the Events directory. 
$ cd Events
Generate a New Component

We can then use the Ionic CLI to generate a new component:

# The Ionic CLI can generate boilerplate code.
$ ionic generate component Hello

After we've generated the HelloComponent, we can add it to our app.module.ts:

import {HelloComponent} from '../components/hello-component/hello-component';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    HelloComponent
  ]...
Publish an Event

Within our HomeComponent we can set up a simple template that involves an input element and a button:

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Events
    </ion-title>
  </ion-navbar>
</ion-header>
 
<ion-content padding>
  <hello-component></hello-component>
  <ion-item>
    <ion-label stacked>Name</ion-label>
    <ion-input [(ngModel)]="name"></ion-input>
  </ion-item>
  <button ion-button (click)="publishEvent()">Publish Event</button>
</ion-content>

We can then import the Events service from ionic-angular and inject it inside our constructor.

After we’ve done that, we can hook our publishEvent() function up to the Events.publish() method. It firstly takes a topic name (in this case our topic/event name is called hello) and then any parameters we may want to send across, such as this.name.

import { Component } from '@angular/core';
import { NavController, Events } from 'ionic-angular';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
  name: string;
 
  constructor(private ev: Events, public navCtrl: NavController) {}
 
  publishEvent(){
    this.ev.publish('hello', this.name);
  }
}
Subscribing to an Event

Now that we’ve published an event with a topic of hello, we can subscribe to that event within our HelloComponent.

import { Component } from '@angular/core';
import { Events, ToastController } from 'ionic-angular'
 
@Component({
  selector: 'hello-component',
  templateUrl: 'hello-component.html'
})
export class HelloComponent {
 
  name: string;
 
  constructor(private toast: ToastController, private ev: Events) {
    this.ev.subscribe('hello', name => {
      const toast = this.toast.create({
        message: `Hello ${name}`,
        duration: 3000
      });
      toast.present();
    })
  }
}

You’ll notice that we get the name that we sent across within our subscribe block. We can then do anything we want to that data, such as show it as a toast.

Conclusion

Events allow you to communicate across numerous components by simply publishing an event with some data, and subscribing to that event within your component(s).

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More