Saturday, 24 February 2018

How to Implement Pull To Refresh functionality in Ionic 2 and ionic 3

Ionic Framework Comes with a ion-refresher Component that makes it easy for developers to implement pull to refresh content functionality in your ionic application. Pull to Refresh can be used to refresh the already existing items or to add more items to the already existing items like timeline. In this example we will see how to implement pull to refresh functionality which adds an country name to the list every time the list is pulled. This tutorial assumes that you already have the project setup and running.

Create a countrylist page.

Execute below command in your projects command prompt to add countrylist page to your project "pages" folder in "src" directory.


  ionic generate page countrylist
this will generate contrylist folder in your project's src/pages folder. Note : import the countrylist page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "countrylist.module.ts" file in your new page file (ie in countrylist folder). the "app.module.ts" should look something like this after countrylist page is imported.

Modify app.module.ts file

app.module.ts



import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { CountrylistPage } from '../pages/countrylist/countrylist';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    CountrylistPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)

  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    CountrylistPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},

  ]
})
export class AppModule {}


That is all for the app.module file your app should run fine now.

Modify countrylist.html template

Copy and paste the below give code just below the opening content tag ie, ion-content.

countrylist.html


  <ion-refresher (ionRefresh)="doRefresh($event)">
        <ion-refresher-content
        pullingIcon="md-arrow-dropdown"
        pullingText="Pull to refresh"
        refreshingSpinner="crescent"
        refreshingText="Refreshing...">
      </ion-refresher-content>
      </ion-refresher>

above code provide you with all the Customizing options to modify the ui of Refresher Content or you can use the default ui by simply using the below given code.

   <ion-refresher (ionRefresh)="doRefresh($event)">
    <ion-refresher-content></ion-refresher-content>
  </ion-refresher>

Now that the UI part is complete, lets head to the countrylist.ts file to implement the ion-refresher functionality.

Modify countrylist.ts file as shown below.

Copy and Paste the below given code in to your countrylist.ts file.

countrylist.ts


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

    /**
    * Generated class for the CountrylistPage page.
    *
    * See https://ionicframework.com/docs/components/#navigation for more info on
    * Ionic pages and navigation.
    */

    @IonicPage()
    @Component({
    selector: 'page-countrylist',
    templateUrl: 'countrylist.html',
    })
    export class CountrylistPage {
    countryList:any;
    moreCountries:any;
    countryCount = 0;
    constructor(public navCtrl: NavController, public navParams: NavParams) {
        this.countryList = [];
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad CountrylistPage');
        this.moreCountries=["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","St. Lucia","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"]
    }

    doRefresh(refresher) {
        console.log('Begin async operation', refresher);

        this.countryList.push(this.moreCountries[this.countryCount])
        this.countryCount = this.countryCount + 1;

        setTimeout(() => {
        console.log('Async operation has ended');
        refresher.complete();
        }, 100);
    }

    }

What the above code does is, when ever you pull the page down it triggers the ionRefresh event, which intern calls the doRefresh function. the doRefresh function then checks the countryCount and pushes the country from moreCountries array to countryList array, which gets updated in the ionic content view. refresh.complete() completes/stops the refresh process. we have set a timeout here to make sure that the spinner spins until the content is updated. it may help someone, so i'm posting the full html code below. feel free to comment below

full countrylist.html template code


<ion-header>

  
  <ion-navbar>
    
          <button ion-button menuToggle>
              <ion-icon name="menu"></ion-icon>
            </button>
          <ion-title>Countries</ion-title>
    
        </ion-navbar>

</ion-header>


<ion-content padding>

  <ion-refresher (ionRefresh)="doRefresh($event)">
    <ion-refresher-content
    pullingIcon="md-arrow-dropdown"
    pullingText="Pull to refresh"
    refreshingSpinner="crescent"
    refreshingText="Refreshing...">
  </ion-refresher-content>
  </ion-refresher>

  <ion-list no-lines>
    <ion-item *ngFor="let item of countryList" style="font-weight: 600;font-family: roboto;">
      {{item}}
    </ion-item>
  </ion-list>


<div *ngIf="countryList.length == 0" style="height: 100%;position: relative;top: 45%;text-align: center;">
    <div style="font-size: 20px;text-align: center;color: #90949c;">Pull to fetch Countries</div>
</div>
</ion-content>

0 comments:

Post a Comment