Models in Ionic 2

How to Create a Data Model in Ionic 2



·

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');
BONUS CONTENT: Download the source code for a complete working example of this tutorial below:

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.

What to watch next...

  • Mark Rajcok

    Instead of looping through the arrays, you could instead use indexOf():


    removeItem(item) {
    var index = this.items.indexOf(item);
    if(index > -1) {
    this.items.splice(index, 1);
    }
    }

    renameItem(item, title) {
    var index = this.items.indexOf(item);
    if(index > -1) {
    this.items[index].title = title;
    }
    }

    • Good suggestion 🙂

      • Patrick

        Hi josh,,
        Very interesting post.
        But I was wondering how to implement these data models in a sqlite database ?
        Do you have an idea ?

  • Mark Rajcok

    Is the ChecklistModel supposed to have properties title and items, or name and items? Your initial datastructure (this.checklists) has name and items.

    • It was supposed to be title, I’ve changed it now – thanks for picking it up.

  • Pingback: Beginners Guide to Getting Started with Ionic 2 | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Thomas Dussaut

    ng-for changed to ngFor and the usage of # in your HTML is deprecated (you could use let instead)

  • Dwiky

    hey josh where I have to put this hey josh where I have to put this

    • Dwiky

      new ChecklistModel(‘my checklist’);

  • Daniel Archer

    This blog is sick man!
    So, I tried this out but in your example at the very very end it says you can use it anywhere like this “new ChecklistModel(‘my checklist’);” but I cannot use it without adding an array. This is what I have to do to stop typescript from giving me an error.

    this.dataArray = [new ChecklistModel(‘My Checklist’, [‘I have to be here for it to work’])];

    Am I missing something? O.o

  • Gabriel Nakano

    Hey Josh! Thanks for all your posts.
    I’m learning a lot with your tutorials.
    My question is about using Datamodels to show a list of things. Let me explain.
    I want to show a list of products with data coming from firebase. For example

    {
    product1:{}

  • jon

    will this data in the array be deleted on browser refresh? o

  • Tae Hwa Kim

    Thanks for good article