TLDR: Hook you toggle up to the data itself with ngModel, then use ionChange to invert (toggle) the data and push to the cloud.

I remember when the first iPhone came out - one of the slickest things about it was the updated app UI. In particular some of my favourite UI improvements were the picker and the simple toggle.

The iOS toggle in action!

I chuckle sometimes when I think to myself before this toggle we use to literally have check boxes with ‘yes’ or ‘no’ options — but I digress.

To begin with you will need some data from Firestore, lets say we have an app where the user can mark a job as ‘open’ or ‘closed’. This data might be modelled like this:

jobStatus: ‘open’

And our UI would probs look like this:

When toggling the option off we will convert the jobStatus record to ‘closed’.

Step 1: Convert our string to a boolean

First thing we will need to do is to convert this data to a boolean (true or false), with simple functions like so:

job: Job;

jobStatus: boolean; // jobStatus is the boolean version of job.status - it can only be true or false constructor( public navParams: NavParams, ) { this.job = navParams.get('job'); // our getter functions

this.jobStatus = this.job.status === 'open' ? true : false; // note this uses a ternary which is the same as saying if job.status is open set to true otherwise set to false }

The reason we need to do this because Angular does not currently support ternary operators in ngModel (there is an open issue about this btw).

Step 2: Connect our model and our view

Now we need to hook up our toggle to our new jobStatus variable in our template like so:

<ion-toggle [(ngModel)]="jobStatus"></ion-toggle>

Sweèt now our toggle will show as on when the job status is open and vice versa. But wait this won’t send data back you might say!

Step 3: Update the model when our toggle changes

This was the only part that was a little tricky, there is nothing in the Ionic docs about an event that would be fired when the toggle is toggled — wink wink #ionic

A quick google search showed me that the easiest way to do this is with ionChange. I updated my template:

<ion-toggle [(ngModel)]="jobStatus" (ionChange)="updateJobStatus()"></ion-toggle>

Step 4: Update our database

Note: Update your code as needed if using Firebase or another realtime database — the process is the same!

Now all we is a function for responding to changes to our toggle:

public updateJobStatus(): void { // the value of the jobStatus is already controlled by the toggle // so we can send it straight to fb const jobRef: DocumentReference = this.afs.doc(`jobs/${job.id}`).ref; // change our jobStatus boolean back to a string

const jobStatus: string = status === true ? 'open' : 'closed';

jobRef.update({ status: jobStatus, }); }

Notice how we needed to change our jobStatus from a boolean back to a string? That is the final bit of secret sauce.