Saturday, 18 November 2017

HighCharts Column Drilldown Chart Implementation in ionic 2 and 3

HighCharts DrillDown Chart Implementation in ionic 2 and 3 Highcharts are interactive charts for web pages, which makes it easy for developers to integrate live charts in to their project.
In this tutorial we will be working on how to implement HighCharts column drilldown chart in ionic 2 and 3 project.
First of all modify your Project code as shown below,
Note: if you want to check out the code or you only want the code, you can download the component HERE, after downloading just copy and paste the component in to your projects src/pages folder that's it.
Copy & Paste the below code to your Components html page

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

<ion-content padding>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

</ion-content>

this div container with id "container" is the place where the highchart is rendered.
Copy & Paste the ts code to your Components .ts file.


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

declare var Highcharts;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {
    
  }
  
  
  ionViewDidLoad() {
    console.log('ionViewDidLoad DateTimePickerPage');
 this.drilldown();
  }
  
  drilldown(){
     // Create the chart
  Highcharts.chart('container', {
   chart: {
    type: 'column'
   },
   title: {
    text: 'Browser market shares. January, 2015 to May, 2015'
   },
   subtitle: {
    text: 'Click the columns to view versions. Source: netmarketshare.com.'
   },
   xAxis: {
    type: 'category'
   },
   yAxis: {
    title: {
     text: 'Total percent market share'
    }

   },
   legend: {
    enabled: false
   },
   plotOptions: {
    series: {
     borderWidth: 0,
     dataLabels: {
      enabled: true,
      format: '{point.y:.1f}%'
     }
    }
   },

   tooltip: {
    headerFormat: '{series.name}
', pointFormat: '{point.name}: {point.y:.2f}% of total
' }, series: [{ name: 'Brands', colorByPoint: true, data: [{ name: 'Microsoft Internet Explorer', y: 56.33, drilldown: 'Microsoft Internet Explorer' }, { name: 'Chrome', y: 24.03, drilldown: 'Chrome' }, { name: 'Firefox', y: 10.38, drilldown: 'Firefox' }, { name: 'Safari', y: 4.77, drilldown: 'Safari' }, { name: 'Opera', y: 0.91, drilldown: 'Opera' }, { name: 'Proprietary or Undetectable', y: 0.2, drilldown: null }] }], drilldown: { series: [{ name: 'Microsoft Internet Explorer', id: 'Microsoft Internet Explorer', data: [ [ 'v11.0', 24.13 ], [ 'v8.0', 17.2 ], [ 'v9.0', 8.11 ], [ 'v10.0', 5.33 ], [ 'v6.0', 1.06 ], [ 'v7.0', 0.5 ] ] }, { name: 'Chrome', id: 'Chrome', data: [ [ 'v40.0', 5 ], [ 'v41.0', 4.32 ], [ 'v42.0', 3.68 ], [ 'v39.0', 2.96 ], [ 'v36.0', 2.53 ], [ 'v43.0', 1.45 ], [ 'v31.0', 1.24 ], [ 'v35.0', 0.85 ], [ 'v38.0', 0.6 ], [ 'v32.0', 0.55 ], [ 'v37.0', 0.38 ], [ 'v33.0', 0.19 ], [ 'v34.0', 0.14 ], [ 'v30.0', 0.14 ] ] }, { name: 'Firefox', id: 'Firefox', data: [ [ 'v35', 2.76 ], [ 'v36', 2.32 ], [ 'v37', 2.31 ], [ 'v34', 1.27 ], [ 'v38', 1.02 ], [ 'v31', 0.33 ], [ 'v33', 0.22 ], [ 'v32', 0.15 ] ] }, { name: 'Safari', id: 'Safari', data: [ [ 'v8.0', 2.56 ], [ 'v7.1', 0.77 ], [ 'v5.1', 0.42 ], [ 'v5.0', 0.3 ], [ 'v6.1', 0.29 ], [ 'v7.0', 0.26 ], [ 'v6.2', 0.17 ] ] }, { name: 'Opera', id: 'Opera', data: [ [ 'v12.x', 0.34 ], [ 'v28', 0.24 ], [ 'v27', 0.17 ], [ 'v29', 0.16 ] ] }] } }); } }
try running the code now, you will get an error saying "Highcharts" is not declared, that's because we had'nt imported the highcharts js into our app.
Copy & Paste the below CDN links to your index.html.


<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/drilldown.js"></script>

That's it, now save it and run the code. you should see you highcard working.

Friday, 17 November 2017

How to Implement Form Validations in Ionic 2 and 3

We generally implement input fields with [(ngModel)] which uses two way data binding between template and variable, so that what you type or enter in the input field gets binded to variable that is accessible in the .ts file. for example if you have an input field like below:


<ion-input type="text" [(ngModel)]="myInput"></ion-input>


the value you entered in the above input gets binded to this.myInput which can be accesses from respective class definition.
Although the above procedure is fair to use, but if you want to implement validations, it can be somewhat time consuming.
So, to overcome this in this tutorial we are going to learn, how to implement complex form validations ionic 2/3 applications.
Note: if you want to check out the code or you only want the code, you can download the component here, after downloading just copy and paste the component in to your projects src/pages folder that's it.
Now lets get to implemeting form validatons in ionic framework,

We will be using FormGroup & FormControl in this tutorial to create and validate form's in ionic 2/3.
This tutorial assumes that you already have the project created in ionic 2/3.

Copy & Paste the below code to your Components html page


<ion-header>
  
    <ion-navbar>

	    <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
      <ion-title>Form Validation</ion-title>

    </ion-navbar>
  
</ion-header>

<ion-content>
  
<ion-list no-lines>
      <p style="padding: 15px;"><b>Title:</b> A tutorial to demonstrate Form Validations in ionic 2/3.</p>
	  
      <form [formGroup]="signUp" (ngSubmit)="SignUpForm()">

        <ion-item class="itemStyle">
          <ion-label>Name</ion-label>
          <ion-input type="text" formControlName="name" clearInput [class.invalid]="!signUp.controls.name.valid && signUp.controls.name.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Email</ion-label>
          <ion-input type="email" formControlName="email" clearInput [class.invalid]="!signUp.controls.email.valid && signUp.controls.email.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Contact Number</ion-label>
          <ion-input type="number" formControlName="contactnumber" clearInput [class.invalid]="!signUp.controls.contactnumber.valid && signUp.controls.contactnumber.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Password</ion-label>
          <ion-input type="password" formControlName="password" clearInput [class.invalid]="!signUp.controls.password.valid && signUp.controls.password.dirty"></ion-input>
        </ion-item>

        <button ion-button block type="submit" [disabled]="!signUp.valid" style="background-color: #343434;width: 90%;margin: auto;color:white;font-weight: 600;margin-top:20px;">Sign Up</button>
      
      </form>
</ion-list>

</ion-content>



Here, we have a formGroup property with a value of signUp which we are going to create the form with. if not, You might have already observed that we dont have [(ngModel)] here because its work is carried out by formControlName here. every input here has an formControlName which are used to carry and validate input values.
[class.invalid] is applied if the particular formControlName is invalid or dirty. [disabled]="!signUp.valid" disables submit button until the form is valid.
Copy & Paste the ts code to your Components .ts file.


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

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

@IonicPage()
@Component({
  selector: 'page-formcontrol',
  templateUrl: 'formcontrol.html',
})
export class FormcontrolPage {

  private signUp : FormGroup;

  constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder) {
    
    let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    
    this.signUp = this.formBuilder.group({

            name: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])],
            password: ['', Validators.compose([Validators.maxLength(10), Validators.required])],
            email: ['', Validators.compose([Validators.required, Validators.pattern(EMAIL_REGEXP)])],
            contactnumber: ['', Validators.compose([Validators.maxLength(10), Validators.required])],
    
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad FormcontrolPage');
  }
  
  SignUpForm(){
	  console.log(this.signUp.value)
  }

}


dont forget to include this in you .scss file.

Copy and Paste the Below css code to you components .scss file.


    .itemStyle{
        margin-bottom: 15px !important;
        width: 90%;
        margin: auto;
        border-radius: 8px;
        background-color: #eaeaea;
    }  

    .invalid {
		border: 1px solid #f90000;
		border-radius: 5px;
    }


Now that you have all the code in place, lets get to the explanation part, shall we.
Here we are importing Validators, FormBuilder, FormGroup into our page/component from @angular/forms. FormBuilder will be used to create FormGroup which have all the FormControls, which intern have all the values that you entered into the form.
Create a member variable signUp of type FormGroup. Now can use this signUp member variable to create our form.The formBuilder.group function is used to create our FormGroup by supplying an object containing each of our FormControls(ie. formControlName).
Validators.compose function is used to set multiple validators. default validators that are commonly used for validation are,
.Validators.required
.Validators.minLength
.Validators.maxLength
.Validators.pattern


The required validator requires that the value is not empty, minLength and maxLength ensure that the length of the input is of a certain length, and where as pattern uses a regex pattern to validate the form input.

Sunday, 1 October 2017

How to Implement Alert in ionic 2, ionic3 using AlertController.

Alerts are Used to Show important Information to User, it can also be used to require them to make a decision or response from user. Alerts are nothing but type of "floating" modals that appear on top of the app's Content. They are mainly used to give or take information from the user like accepting yes or no, password verification, Information regarding task status etc. Alerts in Ionic are flexible and can also be customized. In this post we learn how to show different types of alerts and how to controll and retrieve data from user when he selects or inputs a value. Note: This post assumes that you already have a working ionic project. Alerts in ionic are of 5 Types: Basic Alerts Prompt Alerts Confirmation Alerts Radio Alerts Checkbox Alerts We will now look in to all the alert types in ionic framework. first lets see how to implement "Basic Alerts", Basic Alerts : Basic Alerts are used to notify the user about any information regarding tasks or processes in the app, a situation where the app requires acknowledgement from user, or a confirmation to the user that an action was done successfully or not.

Copy & Paste the below ts code to your components/pages ts file.


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

@IonicPage()
@Component({
  selector: 'page-alert-controller',
  templateUrl: 'alert-controller.html',
})
export class AlertControllerPage {

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

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

  showBasicAlert() {
    let basicAlert = this.alertCtrl.create({
      title: 'IonicSync.com',
      subTitle: 'A Site where you get to know "How to Implement the basic things" about ionicframework.',
      buttons: ['OK']
    });
    basicAlert.present();
  }

}
Explanation: first we should import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showBasicAlert is the method called when you click on basic alert button. basicAlert.present() initiates the alert and displays it on top of you app's content. Prompt Alerts Prompts gives user a way to input information or data in to the alertbox. Prompt alerts can also be used to ask the user for a password to verify the user, before moving forward in an application’s flow.

Copy & Paste the below showPromptAlert method code to your components/pages ts file.


 showPromptAlert() {
 let promptAlert = this.alertCtrl.create({
   title: 'Register on ionicSync.com',
   message: "Enter a name which will be user as UserName ",
   inputs: [
     {
       name: 'title',
       placeholder: 'Title'
     },
   ],
   buttons: [
     {
       text: 'Cancel',
       handler: data => {
         console.log('Cancel clicked');
       }
     },
     {
       text: 'Submit',
       handler: data => {
         console.log('Saved clicked');
         console.log("Data Entered",data)
       }
     }
   ]
 });
 promptAlert.present();
  }
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showPromptAlert is the method called when you click on prompt alert button. promptAlert.present() initiates the alert and displays it on top of you app's content. when the user clicks on submit button, its handler has the data the user entered in the input field. Confirmation Alerts Confirmation Alerts are used, when it is mandatory that the user should confirm a particular choice before progressing forward in the app. An example of the Confirmation Alert is checking to make sure that the user wants to delete or remove a contact from their address book.

Copy & Paste the below showConfirmAlert method ts code to your components/pages ts file.


showConfirmAlert() {
    let confirmAlert = this.alertCtrl.create({
      title: 'Are you Sure you want to delete this contact?',
      message: 'Do you agree to use this lightsaber to do good across the intergalactic galaxy?',
      buttons: [
        {
          text: 'Disagree',
          handler: () => {
            console.log('Disagree clicked');
          }
        },
        {
          text: 'Agree',
          handler: () => {
            console.log('Agree clicked');
            // Your Imagination should go here
          }
        }
      ]
    });
    confirmAlert.present();
  }
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showConfirmAlert is the method called when you click on confirm alert button. confirmAlert.present() initiates the alert and displays it on top of you app's content. when the user clicks on Agree button, the code to delete the contact goes inside agree handler. Radio Alerts Radio Alerts are similar to that of Confirmation Alert, but it uses the Radio component to offer several choices for user. A set of options is provided to the user, but user can only select one option.

Copy & Paste the below showRadioAlert method ts code to your components/pages ts file.


  showRadioAlert () {
    let radioAlert = this.alertCtrl.create();
    radioAlert.setTitle('Your Order');

    radioAlert.addInput({
      type: 'radio',
      label: 'Burger',
      value: 'burger',
      checked: true
    })
 radioAlert.addInput({
      type: 'radio',
      label: 'Pizza',
      value: 'pizza',
      checked: false
    })
 radioAlert.addInput({
      type: 'radio',
      label: 'Coffee',
      value: 'coffee',
      checked: false
    })
 radioAlert.addInput({
      type: 'radio ',
      label: 'Noodles',
      value: 'noodles',
      checked: false
    });

    radioAlert.addButton('Cancel');
    radioAlert.addButton({
      text: 'OK',
      handler: data => {
   console.log("Ordered",data)
        this.testRadioOpen = false;
        this.testRadioResult = data;
      }
    });
    radioAlert.present();
  }
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showRadioAlert is the method called when you click on radio alert button. radioAlert.present() initiates the alert and displays it on top of you app's content. when the user selects any one of the radio option's and click on ok, he selected option data is send to radiobutton handler. Checkbox Checkbox Alerts are similar to that of Confirmation Alert, but use the Checkbox component to offer multiple choices. They offer the user a set of options to choose.

Copy & Paste the below showRadioAlert method ts code to your components/pages ts file.


  showCheckboxAlert() {
    let checkboxAlert = this.alertCtrl.create();
    checkboxAlert.setTitle('Which planets have you visited?');

    checkboxAlert.addInput({
      type: 'checkbox',
      label: 'Alderaan',
      value: 'value1',
      checked: true
    });

    checkboxAlert.addInput({
      type: 'checkbox',
      label: 'Bespin',
      value: 'value2'
    });

    checkboxAlert.addButton('Cancel');
    checkboxAlert.addButton({
      text: 'Okay',
      handler: data => {
        console.log('Checkbox data:', data);
        this.testCheckboxOpen = false;
        this.testCheckboxResult = data;
      }
    });
    checkboxAlert.present();
 this.testCheckboxOpen = true;
  }
 
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showCheckboxAlert is the method called when you click on checkbox alert button. checkboxAlert.present() initiates the alert and displays it on top of you app's content. when the user selects one or multiple checkbox option's and click on ok, he selected option data is send to radiobutton handler. Finally modify the your components html file as below.

Copy & Paste the below code to your components html file.



<ion-header>

  <ion-navbar>
    <ion-title>Alert Controller</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>

  <ion-item-group>
    <ion-item-divider color="light">Basic Alerts</ion-item-divider>
       <button ion-button full (click)="showBasicAlert()">Basic</button>    
    <ion-item-divider color="light">Prompt Alerts</ion-item-divider>
       <button ion-button full (click)="showPromptAlert()">Prompt</button>    
    <ion-item-divider color="light">Confirmation Alerts</ion-item-divider>
       <button ion-button full (click)="showConfirmAlert()">Confirmation</button>    
    <ion-item-divider color="light">Radio Alerts</ion-item-divider>
       <button ion-button full (click)="showRadioAlert()">Radio</button>    
    <ion-item-divider color="light">Checkbox</ion-item-divider>
       <button ion-button full (click)="showCheckboxAlert()">Checkbox</button>    
  </ion-item-group>
</ion-content>
<ion-footer >
  <ion-toolbar>
    <ion-title>IonicSync.com</ion-title>
  </ion-toolbar>
</ion-footer>

Sunday, 24 September 2017

How to Implement scrollToBottom and scrollToTop in Ionic 2 / Ionic 3.

The Content component in ionic is the place where you write your apps ui part, it provides an easy to use content area with some methods to control the scrollable area. There should only be one content in a single view component. you may be in a situation where, you want to scroll to the bottom of the content. this post explains you on how to scroll to bottom of the page & how to scroll to bottom of the page or to a particular position in the content area. This post assumes that you already have a working ionic project.

Copy & Paste the below Html code to your ionic page.


 <ion-header>
  <ion-navbar>
    <ion-title>Content Scroll</ion-title>
  </ion-navbar>
    <ion-toolbar>
      <ion-grid>

        <ion-row>

          <ion-col col-4>
            <button ion-button block color="danger" (click)="scrollToBottom()">Scroll to Bottom</button>
          </ion-col>

          <ion-col col-4>  
            <button ion-button block color="danger" (click)="scrollToTop()">Scroll to Top</button>
          </ion-col>

          <ion-col col-4>
            <button ion-button block color="danger" (click)="scrollTo()">Scroll to Position</button>
          </ion-col>

        </ion-row>

      </ion-grid>
  </ion-toolbar>
</ion-header>
<ion-content>

  <ion-list no-lines>
   <button ion-item *ngFor="let item of items" style="background: #cdcfd2;margin-bottom: 4px;">
     {{ item }}
   </button>  
  </ion-list>

</ion-content>

<ion-footer>
  <ion-toolbar >
    <ion-title>Powered By IonicSync.com</ion-title>
  </ion-toolbar>
</ion-footer>
Above, code has nothing special, it has ion-header with three buttons that call, three methods scrollToBottom,scrollToTop & scrollTo.

Copy & Paste the below ts code to your Component ts file.



import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,Content } from 'ionic-angular';
/**
 * Generated class for the ContentResizePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-content-resize',
  templateUrl: 'content-resize.html',
})
export class ContentResizePage {
  @ViewChild(Content) content: Content;

  public items:any = [];

  constructor(public navCtrl: NavController, public navParams: NavParams) {
   for(let i=0;i<300;i++){
    this.items.push("item"+"-"+i);
   }
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ContentResizePage');
  }
  
  scrollTo() {
    // set the scrollLeft to 0px, and scrollTop to 500px
    // the scroll duration should take 200ms
    this.content.scrollTo(0, 500, 200);
  }

  scrollToTop() {
    // Scrolls to the top, ie 0px to top.
    this.content.scrollToTop();
  }

  scrollToBottom() {
    // Scrolls to the Bottom of the content area.
    this.content.scrollToBottom();
  }

}

The above .ts code contains ViewChild decorator, which is used to get access to the Content component and its methods. By using the local "content" variable, we now call the scrollToTop() method to scroll to the top of the content area or scrollToBottom() method to scroll to the bottom of the content area. We cal also call scrollTo() method to scroll to a particular position, which takes 3 parameters. first one is scrollLeft to, which specifies the position from left & second is scrollTop to, which specifies to which pixels to slide to & third one is duration in milliseconds.

Sunday, 27 August 2017

How to Implement Split Pane in Ionic framework.

ionicframework SplitPane is a component that makes it possible to create multi-view layout.Similar to iPad apps, SplitPane allows UI elements, like Menus, to be displayed as the viewport increases.The new SplitPane component is perfect for apps that target desktops and large tablets. The SplitPane component is very easy to use and If the devices screen size is below a certain size, the SplitPane will collapse and the menu will become hidden again.

To use SplitPane, Simply add the <ion-split-pane> around your root component ie. <ion-nav>, and add the main attribute to it . In this example, we'll be using a sidemenu layout template.

Code to implement SplitPane in ionic 2, just copy and paste in app.html


<ion-menu [content]="content">
    <ion-header>
      <ion-toolbar>
        <ion-title>Menu</ion-title>
      </ion-toolbar>
    </ion-header>
   <ion-content>

       <!-- the content body -->
   </ion-content>
  </ion-menu>

  <!-- the main content -->
  <ion-nav [root]="root" #content></ion-nav>

add <ion-split-pane> component to wrap around the main <ion-nav> component like this.

<ion-split-pane>
  <!--  side menu  -->
  <ion-menu [content]="content">
    <ion-header>
      <ion-toolbar>
        <ion-title>Menu</ion-title>
      </ion-toolbar>
    </ion-header>
   <ion-content>

       <!-- content body -->
   </ion-content>
  </ion-menu>

  <!-- main content -->
  <ion-nav [root]="root" #content></ion-nav>
</ion-split-pane>
Now, add the main attribute to it so that Ionic knows what should go in the right part of the ionic split pane, ie the central component on the larger screens.

<ion-split-pane>

  <!-- ... -->

  <ion-nav [root]="root" #content main></ion-nav>

</ion-split-pane>
that's it, now if you play with your browser window by adjusting its layout size. you can see the side menu pane changing. By default, SplitPane will oly appear if the screen is larger than 768px. we can customize this, by using when input property on ion-split-pane component as shown below.

<ion-split-pane when="(min-width: 475px)">

  <!--  side menu  -->
  <ion-menu [content]="content">
  
  </ion-menu>

  <!-- main content -->
  <ion-nav [root]="root" #content main ></ion-nav>
</ion-split-pane>
Ionic SplitPane can alse be given some predefined media queries that can be used. they are "xs", "sm", "md", "lg", and "xl". these specify the minimum width required to split the ionic-pane.

<ion-split-pane when="xs">
...
</ion-split-pane>
here, xs : means min-width is 0px, this will make the split-pane to appear always. sm: means min-width is 576px, this will make the split-pane to appear when the min-width is 576px md: means min-width is 768px,this will show the split-pane when the min-width is 768px (default break point) lg: means min-width is 992px, this will make the split-pane to appearwhen the min-width is 992px xl: means min-width is 1200px, this will show the split-pane split-pane when the min-width is 1200px One can also pass boolean values to it so that, it will trigger SplitPane when the value or expression evaluates to true.

<ion-split-pane [when]="isSmall">
 
</ion-split-pane>
in .ts file above constructer add this

class MySplittPaneClass {

  public isSmall= true;
  constructor(){}

}
or, you can call a method like this

<ion-split-pane [when]="showSplitScreen()">

</ion-split-pane>
in respectedd .ts file add this,

class MySplittPaneClass {

  constructor(){}

  showSplitScreen(){

    if(conditionA){
      return true;
    } else {
      return false;
    }

  }

}

Disable ionSplitPane

to disable or enable split pane in ionic project, use input property "enable". it takes boolean as value. If the value is false, the split-pane will be disabled, ie. the side pane will never be displayed. the enable input property default's to true.

Tuesday, 23 May 2017

How to Implement Action Sheet in ionic 2 with ActionSheet Controller .

Action Sheet in ionic framework is a dialog that lets the user choose from a set of options. It appears on top of the app's content, and must be manually dismissed by the user.
actionsheetionic2

Copy and pase the below ts code to your components ts file.

import { Component } from '@angular/core';
import { ActionSheetController } from 'ionic-angular'
import { NavController } from 'ionic-angular';

@Component({
selector: 'page-contact',
templateUrl: 'contact.html'
})
export class ContactPage {

constructor(public navCtrl: NavController,public actionSheetCtrl: ActionSheetController) {

}
presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
title: 'Select Image Via',
buttons: [
{
text: 'Gallery',
handler: () => {
console.log('Gallery clicked');
}
},
{
text: 'Camera',
handler: () => {
console.log('Camera clicked');
}
},
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
}
]
});

actionSheet.present();
}
}

Now for the html part, just add the following html code to your components html file.

Copy and pase the below code to your components html file.

<ion-content>
  <button ion-button full (click)="presentActionSheet()">Pick Image</button>
</ion-content>

Monday, 22 May 2017

How to Implement ModalController and pass data to modal.

A Modal is similar to page, but it goes over the app's current page and is displayed as a popup page. Modal is generally used to select an item from a group or to make a choice.
A modal uses the NavController to present itself . It is added to the stack similar to how NavController's push works.
A modal is "presented" by calling present method.

ionicModal.present();

after the modal has been presented, The modal can later be closed or "dismissed" from within the component instance by using the ViewController's dismiss method.

Data can be passed to a new modal through create method as the second argument.

let ionicModal = this.modalCtrl.create(ionicModal, { Id: 5 });

The data that is passed through create method, can then be accessed from the opened page/modal by using NavParams.

this.params.get('Id');

Once the Modal work is done with, when the modal is dismissed, we can send back or pass required data from modal to previous page by calling the dismiss method.

this.viewCtrl.dismiss(data)

Now, that the modal is closed, the data is passed from modal is received at onDidDismiss method.

ionicModal.onDidDismiss(data => {
console.log(data);
});

Code to implement ModalController and pass data to modal to and forth


 

MyHomePage ts file.





import { Component } from '@angular/core';
import { ModalController, ViewController } from 'ionic-angular';
import { NavController, NavParams } from 'ionic-angular';
import { DetailsPage } from '../details/details'
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
UserId:any;
UserName:any
constructor(public modalCtrl: ModalController,public params: NavParams) {
this.UserId = this.params.get('id');
this.UserName = this.params.get('name');
}

presentModal() {
let MyNewModal = this.modalCtrl.create(DetailsPage , { name: "kumar"});
MyNewModal.onDidDismiss(data => {
console.log(data);
});
MyNewModal.present();
}

}


details.ts file.



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

@Component({
selector: 'page-details',
templateUrl: 'details.html'
})
export class DetailsPage {

constructor(public viewCtrl: ViewController) {

}

dismiss() {
let data = { 'name':'kumar','id':'12345' };
this.viewCtrl.dismiss(data);
}

}

Sunday, 26 March 2017

How to implement FAB (Floating Action Buttons) in ionic 2

FAB Button (Floating Action Buttons) are buttons that float over the content in a fixed position. generally fab's are used for actions like sharing to other media's etc.

In this post i'm going to implement a fab button list containing social media. I'going  to set the button position at the bottom right corner, so that when the fab button is clicked the fab list will be displayed with an animation on top of the fab button.

Copy and Paste the following code on to your page on which you are likely to show fab button.




<ion-fab right bottom color="fabcustom">
<button ion-fab ><ion-icon name="arrow-dropup-circle"></ion-icon></button>
<ion-fab-list side="top">
<button ion-fab color="fabmini"><ion-icon name="logo-facebook"></ion-icon></button>
<button ion-fab color="fabmini"><ion-icon name="logo-twitter"></ion-icon></button>
<button ion-fab color="fabmini"><ion-icon name="logo-twitch"></ion-icon></button>
<button ion-fab color="fabmini"><ion-icon name="logo-googleplus"></ion-icon></button>
<button ion-fab color="fabmini"><ion-icon name="logo-tumblr"></ion-icon></button>
</ion-fab-list>
</ion-fab>


As i had said earlier, the above code will be displayed as shown below. fab will be positioned at the bottom right and the list will be displayed on top.

fab1

Styling the FAB's


Now that, we have fab working, i would like to change the color of the fab button's as i'm not a fan of ionic's primary color, and also i would like to decrease the size of fab button.
To change the color of the fab button, let's change the variables.scss file a bit.

Change the colors variable as shown below




$colors: (
primary: #387ef5,
secondary: #32db64,
danger: #f53d3d,
light: #f4f4f4,
dark: #222,
fabcustom: #38dbf5,
fabmini: #35acbf
);


as you can see two custom properties are added to colors variable.we will use them to change fab color.

Add newly added properites to fab button's, modified code shown below.




<ion-fab right bottom color="primary">
<button ion-fab ><ion-icon name="arrow-dropup-circle"></ion-icon></button>
<ion-fab-list side="top">
<button ion-fab ><ion-icon name="logo-facebook"></ion-icon></button>
<button ion-fab ><ion-icon name="logo-twitter"></ion-icon></button>
<button ion-fab ><ion-icon name="logo-twitch"></ion-icon></button>
<button ion-fab ><ion-icon name="logo-googleplus"></ion-icon></button>
<button ion-fab ><ion-icon name="logo-tumblr"></ion-icon></button>
</ion-fab-list>
</ion-fab>


Now that we have changed the color of the fab buttons, lets change the size of the fab & fab mini button's, for this also we will modify variables.scss

$fab-size : 46px !default
$fab-mini-size : 36px !default;



fab2
that's it for the styling.leave a comment for any queries.

Thursday, 23 March 2017

How to Implement Toast in Ionic 2 with ToastController

A Toast is a short notification that is commonly used on modern applications. it is commonly used to provide feedback/ indicate user  about a particular task's status or to simply display a short message.Toast can be displayed either on the top of the screen or on the bottom area.

Ionic 2 makes it easy to implement toast on your app's. follow the below steps to implement toast in your ionic 2 app.

Import ToastController from ionic-angular to the component in which you are implementing toast.




import { ToastController } from 'ionic-angular';


Now inject ToastController in your component’s class constructor




constructor(private myToastCtrl: ToastController) {}


Now that we have injected toastcontroller in to our components constructor, we can use myToastCtrl to display toast in our app. copy and paste the below code on to your component class, to display a 3 second toast on your ionic 2 app.




presentMyToast() {

let toast = this.myToastCtrl.create({
message: 'Toast Displayed Successfully! yay!!',
duration: 3000,
position: 'top'
});

toast.onDidDismiss(() => {
console.log('toast Dismissed');
});

toast.present();
}


How the Above Code Works?


when ever presentMyToast() method is called, it create's a toast with "this.myToastCtrl.create()", given it the options message, duration, position as above.

"toast.present()" display's the toast on our application where as "toast.onDidDismiss()" is called when ever the toast is dismissed.

ToastController Advanced Options


message: The message that is shown on the toast, takes string as type.

duration: Milliseconds to wait before hiding the current toast. takes number as type.

position: Where the toast should appear on the screen. default type is string.

cssClass: To add custom styling to toast. default type is string.

showCloseButton: used to show close button on toast. defaults to false,

closeButtonText: Text to display in the close button, if "showCloseButton" option is set to true .

dismissOnPageChange: Whether to close the toast when navigating to a other page/screen.