Search code examples
angularcordovaionic-frameworkcontactsionic-native

how to open contacts in ionic native


My requirement is to open native contact using ionic native. I googled but could not get proper answer

We used this ionic Native contacts plugin

getting all contacts :

this.platform.ready().then(() => {
      var opts = {   
         filter : "M",                                
         multiple: true,        
         hasPhoneNumber:true,                             
         fields:  [ 'displayName', 'name' ]
       };
       contacts.find([ 'displayName', 'name' ],opts).then((contacts) => {
         console.log(contacts);
        this.contactlist=contacts;
      }, (error) => {
        console.log(error);
      })
   })

Solution

  • But remember that in Ionic if you want to use a Native API you must first wait for platform.ready() this event will notify that everything has been loaded and it is ready to use.

    import { Platform } from 'ionic-angular';
    import { Contacts, Contact, ContactField, ContactName } from '@ionic-native/contacts';
    
    constructor(private contacts: Contacts, private plt: Platform) {   
       this.plt.ready().then((readySource) => {
          console.log('Platform ready from', readySource);
          // Platform now ready, execute any required native code
          this.initContacts();
        });
    }
    
    initContacts(): void {
       let contact: Contact = this.contacts.create();
    
       contact.name = new ContactName(null, 'Smith', 'John');
       contact.phoneNumbers = [new ContactField('mobile', '6471234567')];
       contact.save().then(
         () => console.log('Contact saved!', contact),
         (error: any) => console.error('Error saving contact.', error)
       );
    
       // If you want to open the native contacts screen and select the contacts from there use pickContact()
    
       this.contacts.pickContact()
                    .then((response: Contact) => { 
                       console.log(response)
                    });
    }