Getting started with Ionic Framework

The goal of this Ionic tutorial is to build the most complete getting started with Ionic Framework guide ever built. We want to help beginners through their first steps on the Ionic world. As developers, we know that starting with a new technology can sometimes be a bit frustrating so want to help here.

To help you through your Ionic Framework learning process, we created an Ionic app with a question and answer format (Q&A), where users will be able to ask, answer and vote questions. So, in this complete tutorial you will learn all the concepts needed to create your first ionic app!

We will learn enough core Angular and Ionic to get started and gain confidence that we can build any kind of app with Ionic Framework. We will be covering a lot of ground at an introductory level, but also, you will find plenty of references to topics with greater depth.

What is Ionic Framework?

Ionic framework is free and open source. It allows you to build mobile apps easily using web technologies. The good news is: if you can manage to create websites, then you know how to build mobile apps. Ionic Framework offers the best web and native app components for building highly interactive, native and progressive web apps.

You can think of Ionic as the front-end UI framework that handles all of the look and feel and UI interactions your app needs in order to be compelling. It's like a kind of "Bootstrap for Native" but with all the support for a broad range of common native mobile components, slick animations, and incredible design.

Also, it allows developers to design apps for every app store and mobile web, using a unique base code that runs everywhere. We will then see more about creating native Cross-platform apps with Capacitor

Since Ionic version 4 (currently we are in version 5), they became Framework agnostic. What does this means? Since its beginnings Ionic Framework was built to work just with Angular. However, today with the popularity and support of web components this has changed. One of the biggest changes between Ionic 3 and Ionic 4, is that now it's completely agnostic of the base framework (previously this place was occupied only by Angular).

Since the components of Ionic Framework, such as <ion-button>, are now encapsulated as Web Components, it's no longer necessary to bind to a base framework. Web components work with any framework, in fact if you prefer you can not use any Framework at all!

What the Ionic team intended with this change was to show their original vision which was to build a UI Framework that could work with any technology a web developer chooses. This opens the door to future applications that can be created in Vue or in React using the Ionic web components.

Web Components? Shadow DOM? CSS Variables? Stencil? Are you getting lost by all these new and important concepts? Don't worry, we wrote a ionic web components guide covering everything related to Ionic web components.

If you want to learn more about Ionic Framework and the main differences between versions, I suggest you to read Ionic Framework introduction and key components.

Well, now that we've cleared up what Ionic Framework is and the kind of things that can be built with it, I want to talk a bit about IonicThemes.

At IonicThemes, we aim to assist developers and contribute to the software industry by creating high quality content that helps in learning how to make better products. At our core, we're a company about empowering people with tools and services to develop new skills and make a living. Sharing our experiences and providing easy to implement solutions is at the core of IonicThemes soul.

We want to help you learn more about Ionic Framework and also help you creating robust, complete, but above all, nice and user-friendly applications. Most developers have a lot of difficulties designing, and don't tell me they don't because as programmers ourselves we have to go through this every day. It wasn't until we started working with a team of designers that we really realized the difference between a good design and using Ionic's default components.

As Max Lynch Ionic Framework CEO said: "IonicThemes helps you get a real app up and running fast by handling all the boilerplate and design that normally takes weeks. Any Ionic developer should consider getting one and getting to work that much more quickly!"

I honestly think that Ionic 5 Full Starter App is the best and most complete Ionic template that you'll be able to find and it's also worth mentioning that we update it and add features and improvements regularly. Some of the features you'll be able to find in this template are: Firebase Integration, Social Authentication, Google Maps, Video Playlist, Multi Language, Ecommerce, Listings and much more...

At IonicThemes we work with a team of designers and experts in User experience to create templates that have nice and flexible components that are easy to integrate into your app.

Ionic buttons, angular forms, ionic cards, ionic images, you name it. We have a piece of article written for every single one of the categories included on the platform.

It's time to start!

What are you going to learn on this ionic tutorial?

Ionic getting started guide

In this ionic framework tutorial we will build an Ionic 5 example app with a question and answer format (Q&A), where users will be able to ask, answer and vote questions.

The app's home page will have a list of categories. Each category will have a list of questions, and each question will have a list of answers. Users will also have the possibility to vote the questions and the answers (up-vote, down-vote), plus a form for creating questions and answers, similar to StackOverflow.

In our previous tutorials we discussed about Ionic Framework introduction and key components and also how to Setup your development environment to build Ionic apps. We also wrote a post exploring the Structure of an Ionic Application. If you are new to ionic framework you should consider reading these posts before.

This tutorial takes you through the steps of creating an Ionic 5 application in TypeScript. It guides you through every step from setup to a complete featured case, which illustrates the fundamental attributes of an ionic app. Data binding, a sensible project structure, navigation, services, resolvers, dependency injection and remote data access through an API, among others.

We will learn enough core Angular and Ionic to get started and gain confidence that we can build any kind of app using Ionic. We will be covering a lot of ground at an introductory level, but we will find plenty of references to topics with greater depth.

You can download all the source code of this ionic free template by clicking the GET THE CODE button from above. Also, we published an online demo of the app we are going to build in this Getting Started with Ionic guide.

What are we going to build?

This ionic app consists on a CRUD (Create, Read, Update, Delete) of Questions and Answers where users can post new questions and answer others.

It will have the following functionalities:

  • Manage Questions (Create, Read, Delete)
  • Manage Answers (Create, Read, Update, Delete)
  • List all the Questions from a specific Category
  • List all the Answers from a specific Question
  • Vote Questions and Answers (up-votes and down-votes)

This is how the final ionic angular app looks like:

ionic free app
ionic free app
ionic free app

In the following sections you will learn how to:

  • Initialize your application using Ionic CLI
  • Create classes to represent the objects from the model
  • Create pages and components to represent the functionalities and display the user interface
  • Understand Ionic Navigation
  • Create services to access and handle data
  • Connect your Ionic app with a remote API to have access to your backend

Ionic Project Structure

Ionic Project Architecture

After following the setup instructions for creating a new project, let's walk through the anatomy of this particular Ionic app.

Ionic's app typical architecture includes:

  • Modules: They help organize an application into cohesive blocks of functionality by wrapping components, pipes, directives, and services.
  • Components: They are the most basic building block of an UI, and the main way we build and specify elements and logic on the page.
  • Templates: They are used to define a component view. A template looks like regular HTML, with typical HTML element tags, but it also has some differences.
  • Services: Almost anything can be a service, any value, function, or feature that your application needs. A service is typically a class with a narrow, well-defined purpose.
  • Assets: local images or jsons that our app needs.
  • External resources: Databases, API's, etc, are fundamental as they will enable our app to interact with the outside world.

Read about the anatomy of an Ionic App to learn more about each of these core building blocks.

Now, let's go deeper and map the project structure to the app's architecture, so we can fully comprehend how all the pieces interact with each other.

Root folder

ionic root folder

In the root of the project we have the following important files and folders:

/e2e

This folder is for the end to end tests of our app. By default Ionic Angular apps use Protractor to build e2e tests.

/node_modules

The npm packages installed in the project with the npm install command.

/platforms

When building the Ionic app for different platforms (such as iOS or android) using Cordova, this folder will be automatically generated with all the files needed.

/plugins

When building the Ionic app for different platforms (such as iOS or android) using Cordova, this folder will be automatically generated with the required Cordova plugins like keyboard or splashscreen.

/resources

When building the Ionic app for different platforms (such as iOS or android), this folder will be automatically generated with the app resources such as the logo and the splash screen image. You should put your own resources here.

/ios

When building the Ionic app for iOS using Capacitor, this folder will be automatically generated with the native iOS project. This folder should be considered part of your Ionic app, this means you need to check it into your source control and edit it in XCode. Get more information about Capacitor.

/android

When building the Ionic app for Android using Capacitor, this folder will be automatically generated with the native Android project. This folder should be considered part of your Ionic app, this means you need to check it into your source control and edit it in Android Studio. Get more information about Capacitor.

/src

This is the most important folder and where the majority of the app will be developed. Here we have all the files that make our ionic app and is the location where we will spend most of our time. We will see more details about this directory in a few paragraphs.

/www

This folder is generated automatically when you build your ionic app and you shouldn't change anything from here. It's where all the compiled files will go.

angular.json

Main configuration file for the Angular CLI. It's created by default when you start a new Ionic Angular project using the Ionic CLI.

package.json

As every modern web application, we need a package system and package manager to handle all the third-party libraries and modules used by our app. Inside this file you will find all the dependencies and some other handy stuff like the npm scripts that will help us orchestrating the development (bundling and compiling) workflow.

package-lock.json

Is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

tsconfig.json

Main configuration file, it needs to be in the root path as it's where the typescript compiler will look for it.

tsconfig.app.json

This file extends tsconfig.json main file and adds some specific configurations for the app. It's then used on angular.json.

Src folder

ionic app component

Inside the src directory we find our raw, uncompiled code. This is where most of the work for an Ionic app will take place. When we run ionic serve, our code inside src/ is transpiled into the correct Javascript version that the browser understands (currently, ES6). That means we can work at a higher level using TypeScript, but compile down to the older form of Javascript the browser needs.

In the root of the project we have the following important files and folders:

/app

Has all the components, modules, pages, services and styles you will use to build your app. Will see more details below.

/assets

You can use this folder to store any images, jsons, and any other asset you may require in your ionic app.

/environments

Under this folder are configuration files used by the Angular CLI to manage the different environment variables. For example, we could have a local database for our development environment and a production database for production environment. Note that when running ionic serve the app uses by default the development environment.

/theme

Here you will find all the variables, mixins and shared styles that will make your application customizable and extendable.

Maybe you don't know Sass? Briefly, it is a superset of css that will ease and speed your development cycles incredibly.

A new Ionic app by default includes variables.scss file. In this file you will find all the colors used within the app. Having those in variables is a good practice and will enable you to play around and try different color schemes easily.

index.html

This is the main entry point for the app where we usually set up scripts and CSS includes.

main.ts

The file where our app is bootstraped.


Let's now see what we have inside our App folder.

App folder

ionic app component

The App folder is the largest folder because it contains all the code of our ionic app. It has all the components, modules, pages, services and styles you will use to build your app. This is the core of the project. Let's have a look at the structure of this folder.

app.component.html

This serves as the skeleton of the app. Typically has a ion-router-outlet to render the routes and their content. It can also be wrapped with content that you want to be in every page such as a side menu like we did in this Ionic 5 free starter app.

app.component.ts

It's the Angular component that provides functionality to app.component.html.

Conventionally, it is the default entrance component for Ionic Framework Angular Apps. Also, in this component you will get notified when the platform is ready and our plugins (Cordova, Capacitor or Ionic Native stuff) are available. That enables you to do any higher level native things you might need. By default, the ionic apps generated by the Ionic CLI set the Status Bar styles and hides the Splash Screen once the app is ready.

app-routing.module.ts

Here we define the main routes for the navigation of the app. Child routes of other lazy modules are defined inside those modules. These routes are registered to the Angular RouterModule in the AppModule.

app.module.ts

This file is the entry point for our app and the main Angular module NgModule of the ionic project.

app.component.scss

The styles file for our AppModule. In this ionic 5 app we define the styles for our Ion Menu.

/learn and /questions

These folders are specific to this ionic example app project. As mentioned before, this app is a Questions and Answers Ionic Starter App. Inside these folders we organized all the pages created for this ionic framework project. We used the Ionic CLI to generate all the scaffolding of the app. We created a SCAFFOLDING.md file with all the commands we used to generate the structure of this app.

Each page has its own folder. Within that folder you will find every related file for that page. This includes the html for the layout, Sass for the styles, typescript for the page component, the specific routing file for this module (because we use lazy routes), the module file and the route resolver (when needed).

app.service.ts

A service is typically a class with a narrow, well-defined purpose. Angular distinguishes components from services to increase modularity and reusability. By separating a component's view-related functionality from other kinds of processing, you can make your component classes lean and efficient.

For our Building a Complete mobile app with Ionic and Angular tutorial we created an AppService with all the tasks related to data access. This service is the responsible of the communication with our API to bring all the data needed by the app.

We will go deeper about Angular Services in a few minutes.

Let's see the structure of a specific module.

Categories Module

Let's have a closer look at the Categories Module from the ionic project of this tutorial located in src/app/learn/categories/

Inside this folder we will find:

categories-listing-page.component.html

This file is for the layout of the page and is also known as the page template. Ionic apps are made of high-level building blocks called Ionic Components, which allow you to quickly construct the UI for your app. Ionic Framework includes a number of components, including cards, lists, and side menus. On this free ionic angular starter app we make use of them to build our beautiful Q&A example.

learn-categories-routing.module.ts

In this project we use lazy loading routes so we need a routing file specific to each module to define the module routes.

categories-listing-page.component.ts

This typescript file is for the page component. Here you will find the functionality and interactions of the page and is where the view logic should go.

categories-listing-page.component.scss

The styles specific for this page should go here.

categories-listing-page.component.spec.ts

This file is to build the tests related to this Component.

categories-listing-page.component.resolver.ts

Angular Route Resolves are a special kind of route guards. They enable us to pre-fetch data from the server before navigating to a route. This way, the data is ready the moment the route is activated. Learn to Handle Data in Ionic with Angular Resolvers

Ionic App Navigation

Ionic Navigation

Navigation is one of the most important parts of an app. Solid navigation patterns help us achieve great user experience while a great router implementation will ease the development process and at the same time make our apps discoverable and linkable.

Ionic Angular apps rely on the Angular Router. The Angular Router is a solid, URL based navigation library that eases the development process dramatically and at the same time enables you to build complex navigation structures. In addition, the Angular Router is also capable of Lazy Loading modules, handle data through page transitions with Route Resolvers, and handling Route Guards to fine tune access to certain parts of your app.

As Ionic positions itself as the best tool to build Progressive Web Apps, and the Discoverable and Linkable principles are fundamental to PWAs, it is clear why the Ionic Navigation relies on the Angular Router.

Discover everything you can do with the Ionic Navigation and learn some usability tricks you can add to your Ionic Framework apps to make them look even better in this complete guide about navigation in Ionic Angular apps.

If you need help with the navigation of your Ionic app, I suggest you to take a look at Ionic 5 Full Starter App - The most complete Ionic Template. It will save you LOTS of development and design time. It has different types of navigations that you can reuse in your apps.

Auth in Ionic 5
Ionic 5 authentication
Ionic 5 log in

Router Link

We can use the routerLink directive to navigate between routes. For example, in the following code, when we press the button we will navigate to the Sign Up page.

<ion-button [routerLink]="['/auth/signup']">
  Sign Up
</ion-button>

routerLink works on a similar idea as a typical href, but instead of building out the URL as a string, it can be built as an array, which can provide more complicated paths.

Given the following route configuration:

{
	path: 'learn/:category',
	loadChildren: () => import('./learn/category/learn-category.module').then(m => m.LearnCategoryModule)
}

It creates a static link to the following route (where Capacitor is the parameter):

<a routerLink="/learn/capacitor">Learn Capacitor</a>

Some notes about navigation UX in Ionic Apps

Before your start thinking about navigation, your must consider the type and amount of data you want to display in your app. Don't forget you will use navigation to show and structure your data, that's why it should follow the information structure of your app and not the other way round.

It is important to keep the best practices for navigation design. This ensures that people will be able to use and find the most valuable features in your app.

Good navigation, like good design, is invisible.

We can classify navigation patterns in many ways, but for this ionic beginners guide we followed this convention: Primary Navigation and Secondary Navigation.

Primary Navigation Patterns

Persistent Navigation

Persistent navigation encapsules menu structures like Tab Menu or the List Menu. When you open an app with this type of navigation, you'll notice right away what are the options for the primary navigation.

Some of the mobile persistent navigation patterns you can use in your Ionic Applications are:

Transient Navigation

Transient navigation has to be revealed in an explicit way through a gesture or tap. This is because of the change in screen size with smartphones, which have made designers to think "outside of the box", literally. These normally include Side Menus and other off-canvas elements.

Transient as a term means staying a short time, which is how the following navigation menus actually work. They are normally hidden until we make an action to reveal them; then making a selection and they disappear again.

Some of the mobile persistent navigation patterns you can use in your Ionic apps are:

When to use them?

It's important to ask yourself these questions when deciding when to use persistent and transient navigation on your ionic app:

  • Is your application "flat"? Are the menu categories equivalent in hierarchy, and are there just a few primary categories (i.e., three to five) in the app?
  • Do your users need the menu to be always visible for quick access?
  • Do the menu categories have status indicators, like the number of unread emails, for instance?

Did you answer any of these questions with a yes? Then you'll probably need to choose persistent navigation.

Secondary Navigation Patterns

You can combine a primary navigation pattern with a secondary navigation pattern to help you better navigate the information structure. The primary navigation patterns may also serve as secondary navigation patterns. It's common to see Tabs with Tabs, Tabs with Lists, Tabs with a Dashboard, a Springboard with a Gallery, and more.

Some of the mobile secondary navigation patterns you can use in your Ionic apps are:

  • Page Swiping
  • Scrolling Tabs
  • Accordion
Find more information about how to design a good navigation strategy for your Ionic Applications.

Improve the design of your Ionic app

ionic design

Ionic Components

Ionic apps are made of high-level building blocks called components, which allow you to quickly construct an interface for your app. These include modals, popups, cards and many others. They are reusable UI elements that serve as the building blocks for your mobile app, made up of HTML, CSS, and sometimes JavaScript.

Every Ionic component adapts to the platform on which your app is running. This is called Platform Continuity and you can find more information in the Theming section of the Ionic Framework documentation.

On the Ionic 5 example app we built for this getting started with Ionic tutorial, we have different layouts. Here's a short list with the most important components we used for each page.

Categories Listing Page

This is the home page of our app. It contains a list of the different categories available on the app. Also it contains a side menu to filter categories by tags.

Ionic Components used on this page:

  • Ion Card: for the categories.
  • Ion Menu: a side menu to filter by tag.
  • Ion Badge: for the selected tag.
  • Ion Toolbar
  • Ion Header

Category Details Page

A page that expands the details of a particular Category. These details include a short description of the category and a list of the questions related to this category. On this page you have the possibility to Delete a question and to Create a new one.

Ionic Components used on this page:

  • Ion Card: for the question details.
  • Ion Badge: for the selected category.
  • Ion Button
  • Ion Grid: Ion Row and Ion Col to display the question votes, answers and delete action.
  • Ion Toolbar
  • Ion Header
  • Ion Modal: to create a new question.
  • Ion Input: for the Create Question Form
  • Ion Alert: to confirm question deletion.

Question Details Page

A page to list the answers of a particular question. On this page you have the possibility to Create a new answer and Update or Delete an existing one. Also, you can vote the question and any of their answers.

Ionic Components used on this page:

  • Ion Card: for the question details.
  • Ion Badge: for the selected category.
  • Ion Button
  • Ion Grid: Ion Row and Ion Col to display the answer votes.
  • Ion Toolbar
  • Ion Header
  • Ion Modal: to create a new answer and to update an existing one.
  • Ion Input: for the Create and Update Answer Forms
  • Ion Alert: to confirm answer deletion.

Ionic's UI components display beautifully on all mobile devices and platforms as they adapt to each platform best practices and style guides.

To perform the Create and Update operations we need forms. Forms are usually one of the major interaction points between an app and the user, so it's important to build them right. Developing good forms requires design and user experience skills so if you need help with this check this ionic forms tutorial to learn how to use and validate form in Ionic apps.

Responsive Grid

The grid in ionic framework is a powerful mobile-first flexbox system for building custom layouts. It is heavily influenced by Bootstrap's grid system.

How does the Ionic Grid work?

The grid is basically composed of three units — a Grid, Row(s) and Column(s).
Grids act as a container for all rows and columns.
Rows are horizontal groups of columns that line the columns up properly.
Content should be placed within columns, and only columns may be immediate children of rows.
Columns will expand to fill their Row, and will resize to fit additional Columns.
It is based on a 12 Column layout with different breakpoints based on the screen size.
The number of columns and breakpoints can be fully customized using Sass.
Learn more about the responsive grid in ionic framework.

Sass

Sass is a stylesheet language that compiles to CSS and is used by Ionic. Sass is like CSS, but with extra features such as variables, mixins, and loops.

We love Sass because it's like css with super powers and because it goes hand in hand with Ionic Framework!

CSS on its own can be fun, but stylesheets are getting larger, more complex, and harder to maintain. This is where a preprocessor can help. Sass lets you use features that don't exist in CSS yet like nesting, mixins, inheritance and other nifty goodies.

CSS Variables

Ionic components are built with CSS Variables for easy customization of an application. CSS variables allow a value to be defined in one place, then used in multiple other places. They also make it possible to change CSS dynamically at runtime. CSS variables allow to easily override Ionic components to match your app colors.

If the words Web Components, Shadow DOM or CSS Variables are new to you, you should read Ionic Web Components guide. In this post you will be able to get all these new concepts and learn how they play in the Ionic Framework ecosystem.

Multi Language

An internationalized app looks as a native app in all the languages and regions it supports. The app stores are available in 150 different countries, and internationalizing your app is the first step to reach this global market.

Ionic offers full LTR and RTL support for apps of all languages. If you are building an Ionic Angular application you can use ngx-translate library which is the internationalization (i18n) library for Angular. Create a Multi Language app with Ionic Framework.

In Ionic 5 Full Starter App - PRO version we built an integration with ngx-translate to help you adding multi language support to your Ionic Apps.

The documentation includes a step by step guide that will allow you to add support for different languages in a few minutes.

Ionic RTL app
Ionic Multi Language

Ionicons

Chances are that you will need icons inside your ionic app. That's why the Ionic team built super beautiful and free icons that you can use to make your apps prettier.

Ionicons is a completely open-source icon set with 1,200+ icons crafted for web, iOS, Android, and desktop apps.

Icons can be used on their own, or inside of a number of Ionic components. A great and important thing about Ionicons is that icons can change slightly depending on the platform the app is running.

On the Ionic 5 free template we built for this getting started with Ionic tutorial we used a some ionicons. Download the source code (by clicking the GET THE CODE button from the beginning of this page) to see how easy is to use them on any Ionic app.

Also, if you are wondering how to use custom icons in your Ionic app, check how we did it in Ionic Full Starter App.

App Shell

An App Shell Architecture is useful for getting some initial HTML to the screen fast, typically the skeleton of your UI, but likely does not contain any real data. Think of Shell Elements as cool content placeholders that are shown where the content will eventually be once it becomes available.

A good App Shell implementation consist of two principles: don't block page transitions and show content placeholders while loading the data for the page. There are different ways to achieve these goals and all of them are explained in Improved UX for Ionic apps with Skeleton Loading Screens

Why is App Shell pattern important? Because it improves the users perceived performance. Perceived Performance is a measure of how quick a user thinks your app is, and that;s often more important than it's true speed.

Picture the perception of time as a continuum of different events, if users don’t see any new events regularly then they may perceive slowness. The trick to get around this is to create a mix of skeleton loading screens and animations that occupy their time.

Strive for getting meaningful content to your humans as quickly as possible. Then, once they have something they can read or interact with, add more content on top. Throw in the rest of the styles, fetch the JavaScript needed to obtain a fancier experience, but always provide them with something to do other than stare at a motionless screen!

We are big fans of App Shell components. We really think it changes the whole perception of an app that's why we created lots of beautiful, flexible and reusable app shell components for Ionic Full Starter App Template.

Ionic Skeleton Screens
Ionic Skeleton Screens
Ionic Skeleton Screens

Data Integration

ionic data services

The key to an evolving app is to create reusable services to manage the data requests to your backend.

As you may know, there are many ways when it comes to data handling and backend implementations. In this ionic tutorial we will explain how to consume data from a remote API.

On this post we will not cover how to build your API. However, if you want us to create another post exaplaining how to create a remote API with nestJS and MongoDB, please leave your comment on the comments section below.

We need to worry about handling data requests so in this section we will talk about models and services and how they work together. We encourage the usage of Models in combination with Services for handling data all the way from the backend to the presentation layer.

Models

Domain models are important for defining and enforcing business logic in applications and are especially relevant as apps become larger and more developers work on them.

At the same time, it's important that we keep our applications DRY and maintainable by moving logic out of components themselves into separate classes (models) that can be called upon. A modular approach such as this, makes our app's business logic reusable.

Models are important because handling raw JSON objects can be hard to maintain. Having "real" entity objects which store the data from your server has maintainability and extensibility advantages.

For our ionic example app we created three models: Category, Question and Answer. These models are also present in our NestJS backend. You could use Swagger SDK generator to automatically build an SDK for your API and use it from your Ionic app. This way it won't be necessary to create the entity models in your Ionic app. We followed this approach for another project and it works like a charm.

Angular Services

A service is typically a class with a narrow, well-defined purpose. Angular distinguishes Components from services to increase modularity and reusability. By separating a component's view-related functionality from other kinds of processing, you can make your Component classes lean and efficient.

Ideally, a Component's job is to enable the user experience and nothing more. A Component should present properties and methods for data binding, in order to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a model).

A Component can delegate certain tasks to Services, such as fetching data from the server or API. By defining such processing tasks in an injectable service class, you make those tasks available to any Component.

To make a Service available from a Component we rely on the Dependency Injection pattern. Dependency Injection is widely used in the Angular framework to provide Components with things they need. You can inject a Service into a Component, giving the Component access to that Service class.

Delegating all the data access tasks to a Service, keeps the Component lean and focused on supporting the View. It also makes it easier to unit test the Component with a mock Service.

To learn more about Angular Services, you can read Introduction to services and dependency injection.

In our example app we created just one Service to handle all the requests from the nestJS API. Because our app is small we just used one Service, however, for larger apps it's recommended to create different services by purpose.

Let's see some code of our AppService class.

@Injectable({
  providedIn: 'root'
})
export class AppService {

	constructor(private http: HttpClient) {	}

	getCategories(): Observable<Category[]> {
		return this.http.get<Category[]>(environment.API_URL + 'categories');
	}
}

Each time we add a new service, the Angular injector doesn't know how to create that Service by default. So, after creating services, we have to teach the Angular injector how to make that Service by registering a Service provider.

You must register at least one provider of any Service. The provider can be part of the Service's own metadata (like in the code example above), which makes the service available everywhere, or you can register providers within specific Modules or Components using the following code.

Let's see some examples:

In a Module:

@NgModule({
  providers: [AppService],
	...
})

When we register a provider with a specific @NgModule, the same instance of a service is available to all components in that Module.

In a Component:

@Component({
	selector: 'app-component',
	providers: [AppService],
	...
})

When we register a provider at the component level, you get a new instance of the service with each new instance of that Component.

At root level:

@Injectable({
	  providedIn: 'root'
})
export class AppService {
	...
}

When we provide the Service at the root level, like we did in our ionic example app, Angular creates a single, shared instance of AppService and injects it into any class that asks for it. Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled app if it isn't used by anyone.

So, let's go back to our AppService. As mentioned before, on this service we have all the methods related to data manipulation.

ionic angular service

Connect your Ionic app with a remote API

For this Ionic Angular tutorial we built an API with all the CRUD operations needed by our Ionic question and answers app. Now it's time to see how to interact with this API from our Ionic app.

Get data from a server

Our nestJS API is hosted on AWS so we need an HttpClient to perform the requests. HttpClient is Angular's mechanism for communicating with a remote server over HTTP. To make HttpClient available everywhere in the app you need to import HttpClientModule in the AppModule.

Then, to use HttpClient from our AppService we just inject it into the constructor.

The HttpClient service makes use of observables for all transactions. Learn more about Communicating with backend services using HTTP.

The getCategories() method send a GET request to our server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data once the response is received.

The http.get() method takes two arguments; the endpoint URL from which to fetch, and an options object that you can use to configure the request.

getCategories(): Observable<Category[]> {
	return this.http.get<Category[]>(environment.API_URL + 'categories');
}

We use environment.ts file to define our API url so in this tutorial the environment.API_URL refers to https://q-a-nest-api.ionicthemes.com/. Then, the url we are requestion the categories from is https://q-a-nest-api.ionicthemes.com/categories.

Send data to a server

In addition to fetching data from a server, Angular HttpClient supports other HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data.

For example, to create a question we use the following code:

createQuestion(question: Question) {
	const body = {
		"slug": this.slugify(question.title),
		"title": question.title,
		"description": question.description,
		"categoryId": question.categoryId
	}
	return this.http.post(environment.API_URL + 'questions/insert', body);
}

Remember you can download the source code of the Ionic Angular example app we built for this tutorial to see the complete code of the AppService.

Conclusion

On this getting started with ionic guide we explained the main building block of an Ionic Angular app such as project structure, ionic navigation, and data integration.

For this tutorial we built a complete Ionic 5 Questions and Answers App that you can download for free by clicking the GET THE CODE button from the beginning of this post. This app is similar to StackOverflow where users can ask Questions, add Answers and vote both of them.

Using a starter app is a good way of starting a new Ionic project because it saves us boilerplate time. Also it's a good way of learning by doing because you have working examples of how things should be done.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. That's why we created Ionic 5 Full Starter App - The most complete Ionic Starter App to help you save hundreds of hours of design and development.

Some of the features you will be able to find in this ionic template are: Firebase Integration, Firebase CRUD, Social Authentication, Forms and Validations, Capacitor, examples of how to use google maps, video playlists, internationalization and much more. Also you will get more than 125 ready to use Ionic pages and components such as Profiles, Forms, Cards, Lists, Categories, Listings, eCommerce, and so much more! Try the demo to see all the types of apps you can build with this premium Ionic Starter.

I know, it may sound like a lot to start, but you are free to use just what you need and remove all the rest!

Hopefully, you didn't run into any issues with this Learn Ionic from scratch step by step tutorial, but if you did, feel free to post your comments in the section below.

Would you like to keep learning Ionic Framework? Find lots of ionic framework tutorials in our tutorials section. Also, now that you are more familiar with Ionic Framework, I suggest your to read the following guides: