Ionic 2

How to create and querying contacts in Ionic 2

In this tutorial I am going to show you how to create an Ionic 2 application to search contacts and add new contact to the device. At first adding functionality to add new. Then we will add contacts search functionality. You can find completed project over here.

Let’s get started.

Now create a blank ionic 2 project and add contacts native plugin.

ionic start --v2 ionic2-contacts blank
cd ionic2-contacts
ionic plugin add cordova-plugin-contacts --save

Add New Contact

Then add a new page using this command.

ionic generate page add_contact

 

Module AddContactPage have to include in app module. After adding src/app/app.module.ts file will look like this:

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AddContactPage } from '../pages/add-contact/add-contact';

@NgModule({
    declarations: [
        MyApp,
        HomePage,
        AddContactPage
    ],
    imports: [
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        HomePage,
        AddContactPage
    ],
    providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}

Ionic 2 contactWe have to import few native class in AddContactPage, contact object for the view and addContact method to save new contact. All of these will be included in src/pages/add-contact/add-contact.ts file. Here is the file after the changes done.

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Contacts, ContactField } from 'ionic-native';

@Component({
  selector: 'page-add-contact',
  templateUrl: 'add-contact.html'
})
export class AddContactPage {
	contactObject = {
        displayName: '',
        nickName: '',
        phoneNumber: '',
        phoneType: ''
    }

  constructor(public navCtrl: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    console.log('ionViewDidLoad AddContactPage');
  }

  addContact(newContact:any) {
      var contact = Contacts.create();
      contact.displayName = newContact.displayName;
      contact.nickname = newContact.nickName;
      
      var field = new ContactField();
      field.type = newContact.phoneType;
      field.value = newContact.phoneNumber;
      field.pref = true;
      
      var numberSection = [];
      numberSection.push( field );
      contact.phoneNumbers = numberSection;
      
      contact.save().then((value) => {
          console.log('saved', value);
          this.navCtrl.pop();
      }, (error) => {
      	console.log(error);
      })   
  }

}

From input fields we will take display name, nickname, phone number and phone type. Place all the input fields and save button to trigger save method. In src/pages/add-contact/add-contact.html file this is how it can be done.

<ion-header>
  <ion-navbar>
    <ion-title>Add Contact</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
	<ion-list>
		<ion-item>
			<ion-input type="text" [(ngModel)]="contactObject.displayName" placeholder="Enter Display Name"></ion-input>
		</ion-item>
		<ion-item>
			<ion-input type="text" [(ngModel)]="contactObject.nickName" placeholder="Enter Nick Name"></ion-input>
		</ion-item>
		<ion-item>
			<ion-input type="tel" [(ngModel)]="contactObject.phoneNumber" placeholder="Enter Phone number"></ion-input>
		</ion-item>

		<ion-item>
	        <ion-label>Type</ion-label>
	        <ion-select [(ngModel)]="contactObject.phoneType">
				<ion-option value="home">Home</ion-option>
				<ion-option value="work">Work</ion-option>
				<ion-option value="other">Other</ion-option>
			</ion-select>
	    </ion-item>
	</ion-list>
    
</ion-content>
<ion-footer no-border>
    <button ion-button block (click)="addContact(contactObject)">Save</button>
</ion-footer>

 

Search Contacts

We will create findContact method to find contacts. We will search only displayName ContactFieldType. We want multiple contacts which must have phone numbers filtered by user input. Those contacts array will be assigned to contactsfound variable. Variable contactsfound will be bind to display to show all of them. Here is the code to do these things.

Open up src/pages/home/home.ts and put this code.

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';
import { Contacts, ContactFieldType, ContactFindOptions } from 'ionic-native';

import { AddContactPage } from '../add-contact/add-contact';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
	contactsfound = [];
	search = false;
	
	constructor(public navCtrl: NavController) {
	}

	newContact() {
		this.navCtrl.push(AddContactPage);
	}

	findContact(ev:any) {
		let fields:ContactFieldType[] = ['displayName'];

		const options = new ContactFindOptions();
		options.filter = ev.target.value;
		options.multiple = true;
		options.hasPhoneNumber = true;

		Contacts.find(fields, options).then((contacts) => {
			this.contactsfound = contacts;
			console.log(JSON.stringify(contacts[0]));
		});

		if(this.contactsfound.length == 0){
			this.contactsfound.push({displayName: 'No Contacts found'});  
		}
		this.search = true;
	}
}

Then we will add searchbar to take user input to filter contacts, A list to show those and a button on footer to add new.

Open src/pages/home/home.html and replace everything inside with the code below.

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic 2 Contacts
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
	<ion-searchbar (ionInput)="findContact($event)" placeholder="Enter display name"></ion-searchbar>

	<ion-list [hidden]="!search">
		<ion-item *ngFor="let item of contactsfound">{{item.displayName}}</ion-item>
	</ion-list>
	
</ion-content>

<ion-footer no-border>
	<button ion-button block (click)="newContact()">Add Contact</button>
</ion-footer>

Thank you for reading. Let me know it is going with yours.