Tutorial hero
Lesson icon

How to Create a Data Model in Ionic 2

Originally published November 23, 2015 Time 8 mins

A model in programming is a generic concept, and you may have come across it with common patterns like Model-View-Controller (or MVC). Depending on the context, the exact definition of a model may vary, but in general a model is used to store or represent data.

In this tutorial we are going to walk through how to create a data model in Ionic 2, and talk about why you might want to do that over just manually defining your data.

DISCLAIMER: At the time of writing this, Ionic 2 is still in Alpha and things may change. If you find that the code in this tutorial no longer works, let me know and I’ll do my best to update it.

Before we Get Started

Before you go through this tutorial, you should have at least a basic understanding of Ionic 2 concepts. You must also already have Ionic 2 set up on your machine.

If you’re not familiar with Ionic 2 already, I’d recommend reading my Ionic 2 Beginners Guide first to get up and running and understand the basic concepts. If you want a much more detailed guide for learning Ionic 2, then take a look at Building Mobile Apps with Ionic 2.

Why Create a Data Model?

In the context of Ionic 2 & Angular 2, if we wanted to keep a reference to some data we might just do something like this:

this.myDataArray = ['1', '2', '3'];

However, if were were to create a model it might look something like this:

this.myDataArray = [
  new MyDataModel('1'),
  new MyDataModel('2'),
  new MyDataModel('3'),
];

So instead of storing static data, we are creating an object that holds that data instead. At first it might be hard to see why we would want to do this, but it does provide a lot of benefits. I think these benefits are best explained with an example.

Recently, I was working on creating a new Ionic 2 application and created some test data that looked like this:

this.checklists = [
  {
    title: 'Checklist 1',
    items: [
      { title: 'Task 1', checked: false },
      { title: 'Task 2', checked: false },
      { title: 'Task 3', checked: false },
    ],
  },
  {
    title: 'Checklist 1',
    items: [
      { title: 'Task 1', checked: false },
      { title: 'Task 2', checked: false },
      { title: 'Task 3', checked: false },
    ],
  },
  {
    title: 'Checklist 1',
    items: [
      { title: 'Task 1', checked: false },
      { title: 'Task 2', checked: false },
      { title: 'Task 3', checked: false },
    ],
  },
];

Essentially what I’m creating here is a list of checklists, and each of these checklists has many items. Now I can quite easily use this data in my templates by doing something like this:

<ion-checkbox *ngFor="let item of checklist.items" [checked]="item.checked">
  {{item.title}}
</ion-checkbox>

This will create a checkbox for all of the items in a specific checklist, and it works quite nicely. But let’s say I want to modify my data in some way, for example by adding a new checklist, adding a new item to a specific checklist, deleting items and so on – manually manipulating this data array every time I want to change something would become quite tiresome.

However, if I use a data model, each checklist in my this.checklists array will be an instance of this data model, i.e:

this.checklists = [
  new MyChecklistModel('test'),
  new MyChecklistModel('test2'),
  new MyChecklistModel('test3'),
];

and on that MyChecklistModel model I can define whatever helper functions I like. The obvious functions to create in the model would be something like addItem and removeItem functions, then whenver I want to add or remove an item, I can simply do something like this:

this.checklists[0].removeItem(item);
this.checklists[0].addItem(item);

Which is a lot easier and cleaner than manually manipulating the items array every time we want to change it. Now that I’ve given you a quick overview, let’s take a look at how we might implement a data model properly in Ionic 2.

Creating a Data Model in Ionic 2

First let’s create a new project. Again, if you haven’t already got Ionic 2 set up on your machine, take a look at the tutorials I linked at the beginning of this post.

Generate a new Ionic 2 project by running the following command:

ionic start ionic2-data-model blank --v2

1. Create the Data Model

Create a new file at app/models/checklist-model.ts and add the following

export class ChecklistModel {

    constructor(public title: string, public items: any[]){

    }

    addItem(item){
        this.items.push({
            title: item,
            checked: false
        });
    }

    removeItem(item){

        for(i = 0; i < this.items.length; i++) {
            if(this.items[i] == item){
                this.items.splice(i, 1);
            }
        }

    }
}

If you’ve already been playing around with Ionic 2, then this should look pretty similar to other components you’ve been creating. We’re creating a new class (for those unfamiliar with classes, a class is like a blueprint to create instances of objects – you can create many objects from the same class definition, which is exactly what we will be doing).

The class has a constructor which is run each time it is used to instantiate an object, and we’re using it to set up some data like the title and any items passed in or just an empty array for items. With the constructor set up this way we can either create a new data model like this:

new ChecklistModel('my checklist', itemsArray);

Then we have our addItem and removeItem functions defined, which manipulate the items array for us.

You can take this even further though and add some extra helper functions like this:

Modify checklist-model.ts to reflect the following:

export class ChecklistModel {

    constructor(public title: string, public items: any[]){

    }

    addItem(item){
        this.items.push({
            title: item,
            checked: false
        });
    }

    removeItem(item){

        for(i = 0; i < this.items.length; i++) {
            if(this.items[i] == item){
                this.items.splice(i, 1);
            }
        }

    }

    renameItem(item, title){
        for(i = 0; i < this.items.length; i++) {
            if(this.items[i] == item){
                this.items[i].title = title;
            }
        }
    }

    setTitle(title){
        this.title = title;
    }
}

Now we can also rename items and change the tile of the checklist. We could take this even further still and have an ItemModel model defined so that each item inside of the checklist is also a nice object that we can manage (this would make our ChecklistModel cleaner because we are still manually manipulating the items array here).

2. Import and Use the Data Model

Now that you’ve created the data model, you’ll just need to import it into any component that you want to use it in. You could include it in the home component for example by adding the following line to the top of your home.ts file:

Add the following to the top of the home.js file:

import { ChecklistModel } from '../../models/checklist-model';

then you can use it anywhere simply by using:

new ChecklistModel('my checklist');

Summary

This was a pretty basic example, but it should give you an idea of how and why to use data models in your own applications – especially when your application starts getting more complex and you want to use the data model in multiple places.

Learn to build modern Angular apps with my course