1. Code
  2. Mobile Development
  3. Ionic Development

Creating a Task Manager App Using Ionic: Part 2

Scroll to top

In the first part of the tutorial series, you created the user interface and navigation for the task manager app. In this tutorial, you'll see how to implement the functionality for the Ionic task manager app to add and list tasks.

Getting Started

Let's get started by cloning the source code from the first part of the tutorial series.

1
git clone https://github.com/royagasthyan/IonicTaskManager-Part1

Navigate to the project directory and install the required dependencies.

1
cd IonicTaskManager-Part1
2
npm install

Run your app from the project directory.

1
ionic serve

You should have the application running at http://localhost:8100/.

Communicating Between Components

You have already created the Add component and List component to add tasks and to list tasks respectively. In order to make them work in sync, you need to maintain communication between the two components. To communicate between the components, you'll make use of an injectable CommonService.  

Create a folder called service in the src/pages folder.

Create a service file called common.service.ts and add the following code:

1
import { Injectable } from '@angular/core';
2
3
@Injectable()
4
export class CommonService {
5
 
6
	constructor(){
7
		this.tasks = []
8
	}
9
}

You'll keep track of the tasks list in the common service, and it will be shared between the Add and List components.

Define a variable called tasks in the common.service.ts file. You'll keep your task list in this tasks array.

1
import { Injectable } from '@angular/core';
2
3
@Injectable()
4
export class CommonService {
5
    
6
    public tasks:any;
7
8
	constructor(){
9
		this.tasks = []
10
	}
11
12
}

Create a folder called task inside the src/pages folder. Create a file called task.model.ts and add the following code:

1
export class Task{
2
    constructor(
3
		public Id: Number,
4
		public Name: String,
5
		public IsDone: Boolean
6
	) { }
7
}

You'll use the above Task class to create an instance of a new task.

When the user clicks on the Add task button from the Add component, you'll add items to the tasks variable in the common.service.ts file. So create a method called addTask in the common.service.ts file, which you'll call from the Add component.

1
import { Injectable } from '@angular/core';
2
import { Task } from '../model/task.model'
3
4
@Injectable()
5
export class CommonService {
6
    public tasks:any;
7
8
	constructor(){
9
		this.tasks = []
10
	}
11
12
	addTask(item){
13
		this.tasks.push(new Task((new Date()).getTime(),item,false));
14
	}
15
}

Add a Task to the List

In order to add a task to the task list, you need to import the common.service.ts file inside the AddPage component.

1
import { CommonService } from '../service/common.service'

Initialize the CommonService inside the AddPage component constructor method.

1
  constructor(public viewCtrl: ViewController, private commonService: CommonService) {
2
3
  }

Inside the AddPage component, create a method called add where you'll add the task to the common service tasks list.

Here is how the add method in the AddPage component looks:

1
add(){
2
  this.commonService.addTask(this.item);
3
  this.dismiss();
4
}

As seen in the above method, you have called the addTask method from the common service to add a task to the tasks list.

Once the item is added, you have called the dismiss method to dismiss the pop-up overlay. Here is how the add.component.ts file looks:

1
import { Component } from '@angular/core';
2
import { ViewController } from 'ionic-angular';
3
import { CommonService } from '../service/common.service'
4
5
@Component({
6
  selector: 'page-add',
7
  templateUrl: 'add.component.html'
8
})
9
export class AddPage {
10
11
12
  public tasks: any = [];
13
  public item:String;
14
15
  constructor(public viewCtrl: ViewController, private commonService: CommonService) {
16
17
  }
18
19
  dismiss(){
20
      this.viewCtrl.dismiss();
21
  }
22
23
  add(){
24
  	this.commonService.addTask(this.item);
25
  	this.dismiss();
26
  }
27
28
}

In the add.component.html page, add the ngModel directive to the input element.

1
 <ion-input name="add" [(ngModel)]="item"></ion-input>

Add the click event to the button in the add.component.html to trigger the add method inside the add.component.ts.

1
<button ion-button round (click)="add()">Add</button>

Save the above changes and try to restart the ionic server. Navigate the browser URL to http://localhost:8100, and you should be able to view the mobile app in the browser.

Click on the Add icon to add a task. Enter the task name and click the add button. The pop-up should disappear.

Listing Task List Items

Once the task gets added in the tasks list, you need to update the view accordingly. So, to track the task when added to the list, you'll need to use Angular Subject.

Define a subject called task_subject inside the common.service.ts file.

1
public task_subject = new Subject<String>()

When the task gets added to the tasks list, you need to trigger the subject task_subject to inform the subscriber that a task has been added.

Modify the addTask method inside the common.service.ts file to include the following code:

1
this.task_subject.next();

Here is the modified addTask method:

1
addTask(item){
2
	this.tasks.push(new Task((new Date()).getTime(),item,false));
3
	this.task_subject.next();
4
}

Subscribe to the subject task_subject inside the list.component.ts file.

1
constructor(public modalCtrl: ModalController, public commonService:CommonService) {
2
   this.commonService.task_subject.subscribe(response => {
3
		this.tasks = this.commonService.tasks;
4
	})
5
}

Whenever a new task is added the tasks from the commonService is assigned to the tasks in list.component.html and the view is updated.

Here is how the list.component.ts code looks:

1
import { Component } from '@angular/core';
2
import { ModalController } from 'ionic-angular';
3
import { AddPage } from '../add/add.component';
4
import { CommonService } from '../service/common.service'
5
6
@Component({
7
  selector: 'page-list',
8
  templateUrl: 'list.component.html'
9
})
10
export class ListPage {
11
12
  public tasks=[];
13
  constructor(public modalCtrl: ModalController, public commonService:CommonService) {
14
  	 
15
  	 this.commonService.task_subject.subscribe(response => {
16
			this.tasks = this.commonService.tasks;
17
		})
18
  }
19
20
  presentAddModal() {
21
   let addModal = this.modalCtrl.create(AddPage);
22
   addModal.present();
23
  }
24
25
}

Modify the list.component.html to iterate over the tasks variable from the list.component.ts file. Here is how it looks: 

1
<ion-list>
2
3
  <ion-item *ngFor="let item of tasks">
4
    <ion-label>{{item.Name}} </ion-label>
5
    <ion-checkbox name="chk"></ion-checkbox>
6
  </ion-item>
7
8
</ion-list>

Save the above changes and restart the server. Try to add a new task and it will get displayed on the listing screen.

Ionic Task ManagerIonic Task ManagerIonic Task Manager

Now let's implement the functionality to mark the finished tasks. Each time a new task is added, you are adding an IsDone attribute as false.

Let's keep two different arrays for pending tasks and finished tasks.

1
public pendingTasks = []
2
public doneTasks = []

Each time a new task is added, you'll update the above two arrays as shown:

1
constructor(public modalCtrl: ModalController, public commonService:CommonService) {
2
   
3
  this.commonService.task_subject.subscribe(response => {
4
	this.pendingTasks = this.commonService.tasks.filter(item => {
5
		return item.IsDone == false
6
	});
7
	this.doneTasks = this.commonService.tasks.filter(item => {
8
		return item.IsDone == true
9
	});
10
})
11
}

When the user clicks on the check box, you need to toggle the IsDone status. Add a method called checkPendingItem to toggle the IsDone status for pending tasks.

1
 checkPendingItem(id){
2
      
3
  	this.pendingTasks.map((task) => {
4
      if(task.Id == id){
5
        if(task.IsDone){
6
          task.IsDone = false;
7
        } 
8
        else{
9
          task.IsDone = true;
10
        }
11
      }
12
    })
13
14
15
   this.updateTask()
16
  	
17
  }

Similarly, add another method called checkDoneItem to toggle the task status for done items. Here is how the method looks:

1
checkDoneItem(id){
2
  
3
  this.doneTasks.map((task) => {
4
  if(task.Id == id){
5
    if(task.IsDone){
6
      task.IsDone = false;
7
    } 
8
    else{
9
      task.IsDone = true;
10
    }
11
  }
12
})
13
14
15
this.updateTask()
16
  
17
}

Once the IsDone status is toggled, you need to update the tasks. Define a method called updateTask, which is called after IsDone toggle in both of the above methods.

1
updateTask(){
2
  this.pendingTasks = this.commonService.tasks.filter(item => {
3
	return item.IsDone == false
4
  });
5
  this.doneTasks = this.commonService.tasks.filter(item => {
6
	return item.IsDone == true
7
  });
8
}

Modify the list.component.html code to display the pendingTasks and doneTasks separately. Here is how the modified list.component.html file looks:

1
<ion-header>
2
    <ion-navbar>
3
        <ion-title text-center>Ionic Task Manager</ion-title>
4
    </ion-navbar>
5
6
</ion-header>
7
8
<ion-content padding>
9
    <ion-fab top right>
10
        <button ion-fab mini (click)="presentAddModal()"><ion-icon name="add"></ion-icon></button>
11
    </ion-fab>
12
13
    <ion-card>
14
        <ion-card-header>
15
            My Tasks
16
        </ion-card-header>
17
18
        <ion-list>
19
20
            <ion-item *ngFor="let item of pendingTasks">
21
22
                <ion-label>{{item.Name}} </ion-label>
23
                <ion-checkbox name="chk" (click)="checkPendingItem(item.Id)" [checked]="item.IsDone"></ion-checkbox>
24
            </ion-item>
25
26
        </ion-list>
27
    </ion-card>
28
29
    <ion-card>
30
        <ion-card-header>
31
            Archived Tasks
32
        </ion-card-header>
33
34
        <ion-list>
35
36
            <ion-item *ngFor="let item of doneTasks">
37
38
                <ion-label color="light">{{item.Name}} </ion-label>
39
                <ion-checkbox name="chk" (click)="checkDoneItem(item.Id)" [checked]="item.IsDone"></ion-checkbox>
40
41
            </ion-item>
42
43
        </ion-list>
44
    </ion-card>
45
46
</ion-content>

Save the above changes and restart the ionic server. You should have the application running at http://localhost:8100.

Ionic Task Manager App ListingIonic Task Manager App ListingIonic Task Manager App Listing

Wrapping It Up 

In this tutorial, you saw how to implement the functionality to add and list the tasks in the Ionic task manager mobile app. You saw how to use an Angular service to share data between two components. In this tutorial, you used the Angular service to keep data in a common list when added from the Add component and display it in the List component.

Do let us know your thoughts in the comments below.

Source code from this tutorial is available on GitHub.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.