Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Understanding Ionic 2 Components (Tutorial)

By Gary simon - Jan 20, 2017

Ionic components are simply building blocks for your app. There's a lot of them (28 to be exact), and while we won't cover them all, I will show you how to understand the official documentation. Going forward, this will give you the confidence you need to correctly use any of the components in your Ionic app.

First, if you prefer watching a video..

I've covered everything in this written tutorial in the video tutorial below. Feel free to subscribe to the coursetro youtube channel!

Get a Project Setup

First, to demonstrate how these components work, make sure you have a new project created with the Ionic CLI. If you're following along with this from our free ionic course, then you already have a project setup from the previous lesson and you can skip this step.

If not, refer to this video on how to install the Ionic CLI and start a project. Then run this command at the console:

Then run these commands at the console in your projects folder (wherever that may be):

$ ionic start firstProject blank --v2
$ ...
$ ... let it install
$ ...

$ cd firstProject

$ ionic serve -l

Looking at the Documentation

In a new browser window (or tab) visit the Ionic documentation page. On the left sidebar, we have a components section which extends into a list of all the available Ionic components.

There are two types of components here:

  1. Those that are composed of just HTML and CSS. We'll refer to these as template components. There are 20 of them.
  2. Those that also include interactive, dynamic functionality. We'll call these dynamic components. There are 8 of these.

In both cases, the documentation provides you with information on how to implement the component in the template through custom HTML elements and attributes designated for that particular component.

For the purpose of simplicity, let's first take a look at a template component.

How Template Components Work

Now, just 3 of the 20 template components have no API documentation. That is, they don't accept any type of attributes or options. These 3 are Cards, Grid and Button.

Let's take a look at the card component and see how to implement it.

So, just as a quick example, paste the following HTML in the /src/pages/home/home.html file:

<ion-card>
  <ion-card-header>
    My Amazing Title
  </ion-card-header>
  <ion-card-content>
    And this here is my spectacular content that resides just beneath it.
  </ion-card-content>
</ion-card>

You'll notice after saving, that your app in the browser now shows a simple card-based layout with the above content.

As you can see, it's very easy to implement these types of components. The documentation gives us a few examples, and we're on our way.

But what about the other 17 template components? Let's take a look at the Button component.

These other components have the "For more information, Check out the API Docs" outlined in red above. This links to the API section for that given component.

In the case of the Button component, the API Button documentation provides us with an Input Properties section:

This provides us with all of the possible attributes along with the types of values they accept. Here's a quick example of how to use it, expanding on our previous HTML example:

<ion-card>
  <ion-card-header>
    My Amazing Title
  </ion-card-header>
  <ion-card-content>
    And this here is my spectacular content that resides just beneath it.
    <button ion-button block="true" outline="true" color="danger">Default</button>
  </ion-card-content>
</ion-card>

As you can see, we used 3 of the input properties from the API documentation. Boolean types accept either true or false values, though if it's true, you can simply specify the name of the input property without binding it to a true value.

Let's take a look at another template component. This time, we'll examine the FAB (Floating Action Button) component.

The API documentation for FABs includes an additional section called Attributes:

These are simply HTML attributes that you can add to the HTML element. They accept no values.

Try adding the mini attribute to a FAB element in our HTML, just underneath our previous <button> element:

Let's take a look at one more component in this section, the Select component. The Select API includes 2 other sections:

How would we use an Instance Member?  As we can see, we have an open() method that we can call, which opens the select interface.

Replace all of the HTML in your project with the contents below:

<ion-card>
  <ion-card-content>
    <ion-item>
      <ion-label>Toppings</ion-label>
      <ion-select [(ngModel)]="toppings" multiple="true" #tops>
        <ion-option>Bacon</ion-option>
        <ion-option>Black Olives</ion-option>
        <ion-option>Extra Cheese</ion-option>
      </ion-select>
    </ion-item>
    <button ion-button (click)="openIt(tops)">Open</button>
  </ion-card-content>
</ion-card>

We're creating a reference to ion-select by adding #tops

Then, we've added a (click) event to open a custom method called openIt, while passing in our reference to the select element.

In the home.ts file, add the following code:

openIt(tops) {
  tops.open();
}

Now, click on the button and you'll notice that the select interface is opened. This is how you can use an Instance Member.

Finally, what are Output Events? We can see that the select component has 2 output events: ionChange and ionCancel

We can use event binding on an output event to call a method. So, for instance, if we wanted something to happen when a user cancels out of the select interface, we would adjust our :

<ion-select [(ngModel)]="toppings" (ionCancel)='cancel()' multiple="true" #tops>

Then, in our home.ts file:

cancel() {
  console.log('Cancelled!');
}

Now, if you open the select interface and either click cancel or click anywhere outside of the select interface, we will see "Cancelled!" in the console.

Dynamic Components

There are around 8 components that are also accompanied by controllers. Let's take a look at the Alert component and how to use its' associated controller.

First, replace your HTML with the following:

<ion-card>
  <ion-card-content>
    <button ion-button (click)="openIt()">Open</button>
  </ion-card-content>
</ion-card>

Let's say that we want an alert to popup when a user clicks the Open button. 

In our home.ts file, we first have to import the associated controller with the Alert component. As the Alert API points out, this is called the AlertController.

In the imports, we add:

import { NavController, AlertController } from 'ionic-angular';

Then, in the constructor, we use dependency injection to bind a property to AlertController, so that we can access it throughout our code.

constructor(private alertCtrl: AlertController) {}

And finally, we'll create the openIt() method:

   openIt() {
    let alert = this.alertCtrl.create({
      title: "My Alert",
      subTitle: "My subtitle",
      buttons: [
        {
          text: "Okay"
        },
        {
          text: "Nope"
        }
      ]
    });
    alert.present();
  }

How did I know which methods (such as create) and which properties to use here?

Well, the Alert API provides us with all of that information. Notice that we have a single instance member called create(opts) in the API:

Then, we can see that the opts are defined for us below it with the type of AlertOptions

Further, the AlertOptions and the associated properties are defined beneath it. This is where I got title and subTitle from.

Also, some properties accept array values, such as the buttons property:

So, if you click on the button, you should see the following popup:

Final Thoughts

As you can see, using Ionic components is rather simple, once you understand how to read the documentation. Go ahead and experiment with more components on your own to get a better understanding of how they work!


Share this post




Say something about this awesome post!