top

Search

Ionic Tutorial

To be effective in Ionic, it is essential to have a good knowledge of Angular. Angular is written in TypeScript and most of the syntax required to write an Angular program has been covered, namely - variables, methods, classes, interfaces & modules. UI programming has evolved substantially since the inception of the HTML standard in 1991, CSS in 1994 and of JavaScript (It was then called Mocha) in 1995. Ajax was introduced in 1996.  In 2004, it was implemented in Google Maps and Gmail. BootStrap was created by Twitter in 2012, Angular JS was introduced in 2010. It grew to be the most popular JavaScript framework. It introduced 2-way data binding, dependency injection, routing and more.  Angular 2 was a complete rewrite of AngularJS, and introduced a component based architecture - similar to the emerging JS frameworks like React. Angular 2 comes with a command line interface (CLI), which can be used  to set up a project rapidly and generate components, modules, services, etc. with ease. This enabled web developers to build Single Page Applications which were made up of components which interacted with each other, without having to reload the entire page. The resulting user experience on the web was similar to desktop applications.  As we have seen already, Angular takes full advantage of the object orientation and “future JavaScript now” from TypeScript.Agoda.com is a random example of a single page applicationThis is programmed as separate componentsThey are integrated together using modulesAngular services bring all of it togetherData is fetched by making RESTful API calls to back end applications. Ionic works on exactly the sample principles to build components for a mobile app Typically, most of the user experience is managed in the component. A component, is a typescript class which imports modules from Angular.  The component contains all the data that is required to be displayed to the user and all the data received from the user. Data is bound to different screen elements, like textboxes in the HTML Template via property binding.  Events from screen elements like buttons in the HTML template are bound to functions in the component via event binding. We will look at Angular components, modules, services and directives in this tutorial.  Note that we will not cover CSS and Bootstrap that are used to make the Angular app visually appealing. Installing Angular Once you have installed node, you can go on to install Angular using npm install -g @Angular/cliThis installs the Angular command line interface (CLI). Most of the new files thatAngular needs can be created with skeleton code using the Angular CLI Creating the first Angular project Angular CLI commands start with ng. Ng new <project name> creates a new project ng new AngulartutorialThis will create a new folder Angulartutorial.  Import the folder into Visual Studio Code.Take a few minutes to explore the files created. The source code for the project is stored in the src folder.e2eContains test cases written using Jasminenode_modulesContains NPM modules that will be used for the project.The list of packages to be downloaded are defined in package.json.Running npm install will download the modules from the npm repositorysrcThis folder contains the Angular source code for the projectAngular.jsonConfiguration defaults for Angular CLI. Includes configuration for build, serve, test. You will be able to run most projects with default configurations.editorconfigConfigurations for code editors. https://editorconfig.org/ .gitignoreList of untracked files for git to ignore.package-lock.jsonProvides version information for all npm packagestsconfig.jsonDefault TypeScript configurationtslint.jsonDefault TSLint configuration for apps in the workspace.README.mdIntroductory documentationRunning the first Angular Application On the terminal all you need to do to run the demo application is typeNg serveNg Serve and you will see this on localhost:4200Or use, ng serve --open to directly open the application in a browserUnderstanding the first Angular ComponentThis folder that you just imported into VS Code is the “application shell” which is created when you use ng new.The “app” folder contains the code for the project. The page displayed above is a “view” which consists of a component (ts file) and template (html file). These files can be found in the folder src/appApp.component.html contains the html definition for the view (A view is a combination of an html template and the typescript code). You can make changes to the HTML and observe the changes.Change the heading in line 8 to “We have changed this”. The code compiles again and the page reloads.App.component.ts is the component file, which is a typescript class, is decorated with an annotation @Component (line 3)This class has one variable defined “title” (line 9). Changing the value of this variable will change the title on the html page.On save, the code re-compiles and the page reloads.Here is how it is done in the html.The variable in app.component.ts is referenced in the html using {{}} as {{title}}. This is known as interpolation.  A subtitle can be added by declaring a new variable “subtitle” in app.component.ts and adding {{subtitle}} to app.component.htmlThe styles for this component are setup in app.component.css in the same folderThe heading color can now be set to red in the css fileh1{    color:red;} The page reloads with a red heading 1In summary, 3 parts of an Angular component - the typescript class of the component, the html and the css control the behaviour of the view that has been displayed.  ComponentsThis is a deeper look at the root Angular component that is generated after a ng new.Firstly, the Angular core module is imported into the class.The class is decorated with the @Component annotation which is accompanied with metadata.A CSS selector tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML.In other words, whenever Angular encounters the tags <app-component-selector> </app-component-selector> it will embed this component.templateURL points to the html file linked with the component. Alternatively, the template can be provided inline. Remember to use “template” instead of templateUrlstlyeUrls refers to the css file linked to the component ModulesAngular modules (ngModules) collect related code into functional sets. An Angular app is a collection of ng modules. By default the application shell comes with a default app.module.ts.The Browser Module is an Angular module that allows the Angular app run in a browser.  The ngModule too is a class similar to the Component with a decorator @NgModule. ngModule itself is defined in an Angular module with the same name.  The ngModule decorator has the below metadatadeclarationsThe components, directives, and pipes that belong to this NgModule.exportsThe subset of declarations that should be visible and usable in the component templates of other NgModules.importsOther modules whose exported classes are needed by component templates declared in this NgModule.providersServices that this NgModule contributes to the global collection of services; they become accessible in all parts of the app.bootstrapThe main application view, called the root component, which hosts all other app views. Only the root NgModule should set the bootstrap property.You will notice that the default appComponent that we declared earlier is declared here and is used as the bootstrap component. (Line 14, below)Any module, component, or pipe that is used here needs to be imported first.Creating modules will be covered separately.  Creating a component A component can be created by typing ng generate component <Component Name> Or in short, ng g c <componentName> To create a component called Course, Ng g c courseThis creates 4 files. 3 that we have already seen in the default application component. Html. ts and css files are created. The component.spec.ts is the file that is created for writing automated test cases, which is beyond the scope of this tutorial App.module.ts is automatically updated to import this componentDisplaying the component Note the component metadata for the newly created component and pick up the css selector. In this case app-courseBelow is the default code in course.component.htmlAs we have seen earlier the root view hosts all other views. In order to display the newly created component, embed the selector above in the root component, app.component.htmlWe can now remove the default logo and content of the application shellIn Summary we looked at the ts, html and css files within an Angular component and how they work together. We also looked at how an ngModule brings all the code required for the module together. Directives Structural directives alter layout by adding, removing, and replacing elements in the DOM. The commonly used directives in Angular are *ngIf and *ngFor. You can add or remove an element from the DOM by applying an NgIf directive to that element The expression associated with the *ngIf is evaluated and the element is displayed only if the expression returns true *ngIf In the course.component.ts,We directly assign true and false to *ngIf, the div tag with the value true is displayed and the one with false is not.This can be done using a variable in the course.component.ts file.And in course.component.htmlAnd the output will be:“All Courses” will not be displayed if showHeading = false *ngIf is also used to check for nulls. We now add a class called Course and initialize it as null. We attempt to display its contents in html, but check for null. If the variable “course” is null, the values are not displayed.In html,The output will beBut if we initialize the object like this:The course Object is not null anymore, and will be displayed*ngFor NgFor is a repeater directive — a way to present a list of items. We define a block of HTML that defines how a single item should be displayed. We then tell Angular to use that block as a template for rendering each item in the list. <div *ngFor="let course of courses">{{course.name}}</div> We initialize an array, courses in course.component.ts and use the ngFor in the course.component.htmlIn html.And the output will beIn summary, we looked at *ngFor and *ngIf and how they can be used to dynamically alter the DOM to conditionally display elements and to loop through a list, respectively. ServicesA service contains any value, function, or feature that an app needs. A service is a class with a narrow, well-defined purpose.  A component's function is to enable the user experience A component delegates certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console. You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances. You can inject a service into a component, giving the component access to that service class. The @Injectable() decorator is used to provide the metadata that allows Angular to inject it into a component as a dependency. A service can be generated using the CLI by typing ng generate service <ServiceName> or in short, ng g s <service name>2 files are generated, one is the service file and the other is the test class.In the service file, note the @Injectable annotation. This makes the service available across the applicationWe now define the course array in the service rather than the component. This can be replaced by a HTTP call to an APIIn the course component.ts, the Service is injected via the constructor. The array defined in the service is now assigned to a local variable and the same is referenced in the *ngFor in the HTMLIn summary, this is how dependency injection is done in Angular. A service is defined using the @Injectable annotation and its members are made available across the application. Data Binding Data binding is a mechanism for coordinating what users see, with application data values.  Property BindingBindings between binding sources (variables) and target HTML elements are declared. Angular does the rest of the work.  Property binding is done using square brackets [] <img [src]="heroImageUrl">  <button [disabled]="isUnchanged">Cancel is disabled</button>Property binding is a one-way data binding because it flows a value in one direction, from a component's data property into a target element property. A property binding cannot be used to pull data from an element. It can only be used to set it. An element property between enclosing square brackets identifies the target property. Values can be passed into a component using property binding There is a variable called user in app.component.ts. It is passed to the course.component using [] as follows: App.component.tsApp.component.htmlCourse.component.tsThe input decorator is used to access input parametersCourse.component.htmlAnd the output will beWe have passed the name “Max” from the variable ”user” in app.component.ts  to course.component.ts using input binding. Event BindingUser actions may result in a flow of data in the opposite direction: from an element to a component. Events include being able to listen for certain events such as keystrokes, mouse movements, clicks, and touches.  The target event name is represented within parentheses on the left of an equal sign, and a quoted template statement on the right.  <button (click)="onSave()">Save</button> The event in this case is (click) and the method to be called in the component is onSave() In course.component.html we add a button for the user to express interest. Note that the course name is passed as parameter to the function “expressInterest”We then add the method to display an alert message when the button is clickedNote that we have used a template expression within back-ticks.  On clicking the button the message is displayedWe used brackets () to bind a user event to a function in the component.  Examples of events supported by Angular areMouse events are (click), (mouseover), (mousedown), (mouseenter), (mouseup), (drag), (dragover)  and (dblclick)Keyboard events are (keydown), (keypress), (keyup), (copy), (paste), (cut) Two-way binding Two way binding is done using ngModel. This is used to bind user elements like text boxes and dropdowns to variables in the component. This will allow you to display, listen, and extract at the same time. ngModel is the easiest way to interact with form elements In course.component.ts, add a textbox to take user input of commentsThis is bound to a variable called comment in course.component.tsSummary This was a brief introduction to Angular.We covered: How to create a new Angular app The structure of the Angular app The application shell and the root component The relationship between the component, template and CSS The root module and its structure Services and how they are injected into components Data binding - property binding, event binding, two-way binding This knowledge of Angular is intended to be a springboard into getting started with Ionic.  
logo

Ionic Tutorial

Introduction to Angular

To be effective in Ionic, it is essential to have a good knowledge of Angular. Angular is written in TypeScript and most of the syntax required to write an Angular program has been covered, namely - variables, methods, classes, interfaces & modules. 

UI programming has evolved substantially since the inception of the HTML standard in 1991, CSS in 1994 and of JavaScript (It was then called Mocha) in 1995. Ajax was introduced in 1996.  In 2004, it was implemented in Google Maps and Gmail. BootStrap was created by Twitter in 2012, 

Angular JS was introduced in 2010. It grew to be the most popular JavaScript framework. It introduced 2-way data binding, dependency injection, routing and more.  

Angular 2 was a complete rewrite of AngularJS, and introduced a component based architecture - similar to the emerging JS frameworks like React. Angular 2 comes with a command line interface (CLI), which can be used  to set up a project rapidly and generate components, modules, services, etc. with ease. 

This enabled web developers to build Single Page Applications which were made up of components which interacted with each other, without having to reload the entire page. The resulting user experience on the web was similar to desktop applications.  

As we have seen already, Angular takes full advantage of the object orientation and “future JavaScript now” from TypeScript.

Agoda.com is a random example of a single page application

This is programmed as separate components

They are integrated together using modules

Angular services bring all of it together

Data is fetched by making RESTful API calls to back end applications. 

Ionic works on exactly the sample principles to build components for a mobile app 

Typically, most of the user experience is managed in the component. A component, is a typescript class which imports modules from Angular.  

The component contains all the data that is required to be displayed to the user and all the data received from the user. Data is bound to different screen elements, like textboxes in the HTML Template via property binding.  

Events from screen elements like buttons in the HTML template are bound to functions in the component via event binding. 

We will look at Angular components, modules, services and directives in this tutorial.  

Note that we will not cover CSS and Bootstrap that are used to make the Angular app visually appealing. 

Installing Angular 

Once you have installed node, you can go on to install Angular using 

npm install -g @Angular/cli

This installs the Angular command line interface (CLI). Most of the new files thatAngular needs can be created with skeleton code using the Angular CLI 

Creating the first Angular project 

Angular CLI commands start with ng. Ng new <project name> creates a new project 

ng new Angulartutorial

This will create a new folder Angulartutorial.  Import the folder into Visual Studio Code.

Take a few minutes to explore the files created. The source code for the project is stored in the src folder.

e2eContains test cases written using Jasmine
node_modulesContains NPM modules that will be used for the project.

The list of packages to be downloaded are defined in package.json.

Running npm install will download the modules from the npm repository
srcThis folder contains the Angular source code for the project
Angular.jsonConfiguration defaults for Angular CLI. Includes configuration for build, serve, test. You will be able to run most projects with default configurations
.editorconfigConfigurations for code editors. https://editorconfig.org/ 
.gitignoreList of untracked files for git to ignore.
package-lock.jsonProvides version information for all npm packages
tsconfig.jsonDefault TypeScript configuration
tslint.jsonDefault TSLint configuration for apps in the workspace.
README.mdIntroductory documentation

Running the first Angular Application 

On the terminal all you need to do to run the demo application is type

Ng serve

Ng Serve and you will see this on localhost:4200

Or use, ng serve --open to directly open the application in a browser

Understanding the first Angular Component

This folder that you just imported into VS Code is the “application shell” which is created when you use ng new.

The “app” folder contains the code for the project. The page displayed above is a “view” which consists of a component (ts file) and template (html file). These files can be found in the folder src/app

App.component.html contains the html definition for the view (A view is a combination of an html template and the typescript code). You can make changes to the HTML and observe the changes.

Change the heading in line 8 to “We have changed this”. The code compiles again and the page reloads.

App.component.ts is the component file, which is a typescript class, is decorated with an annotation @Component (line 3)

This class has one variable defined “title” (line 9). Changing the value of this variable will change the title on the html page.

On save, the code re-compiles and the page reloads.

Here is how it is done in the html.

The variable in app.component.ts is referenced in the html using {{}} as {{title}}. This is known as interpolation.  

A subtitle can be added by declaring a new variable “subtitle” in app.component.ts and adding {{subtitle}} to app.component.html

The styles for this component are setup in app.component.css in the same folder

The heading color can now be set to red in the css file

h1{
    color:red;

The page reloads with a red heading 1

In summary, 3 parts of an Angular component - the typescript class of the component, the html and the css control the behaviour of the view that has been displayed.  

Components

This is a deeper look at the root Angular component that is generated after a ng new.

Firstly, the Angular core module is imported into the class.

The class is decorated with the @Component annotation which is accompanied with metadata.

A CSS selector tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML.

In other words, whenever Angular encounters the tags <app-component-selector> </app-component-selector> it will embed this component.

templateURL points to the html file linked with the component. Alternatively, the template can be provided inline. Remember to use “template” instead of templateUrl

stlyeUrls refers to the css file linked to the component 

Modules

Angular modules (ngModules) collect related code into functional sets. An Angular app is a collection of ng modules. 

By default the application shell comes with a default app.module.ts.

The Browser Module is an Angular module that allows the Angular app run in a browser.  

The ngModule too is a class similar to the Component with a decorator @NgModule. ngModule itself is defined in an Angular module with the same name.  The ngModule decorator has the below metadata

declarationsThe components, directives, and pipes that belong to this NgModule.
exportsThe subset of declarations that should be visible and usable in the component templates of other NgModules.
importsOther modules whose exported classes are needed by component templates declared in this NgModule.
providersServices that this NgModule contributes to the global collection of services; they become accessible in all parts of the app.
bootstrapThe main application view, called the root component, which hosts all other app views. Only the root NgModule should set the bootstrap property.

You will notice that the default appComponent that we declared earlier is declared here and is used as the bootstrap component. (Line 14, below)

Any module, component, or pipe that is used here needs to be imported first.

Creating modules will be covered separately.  

Creating a component 

A component can be created by typing ng generate component <Component Name> 

Or in short, ng g c <componentName> 

To create a component called Course, 

Ng g c course

This creates 4 files. 3 that we have already seen in the default application component. Html. ts and css files are created. The component.spec.ts is the file that is created for writing automated test cases, which is beyond the scope of this tutorial 

App.module.ts is automatically updated to import this component

Displaying the component 

Note the component metadata for the newly created component and pick up the css selector. In this case app-course

Below is the default code in course.component.html

As we have seen earlier the root view hosts all other views. In order to display the newly created component, embed the selector above in the root component, app.component.html


We can now remove the default logo and content of the application shell

In Summary we looked at the ts, html and css files within an Angular component and how they work together. We also looked at how an ngModule brings all the code required for the module together. 

Directives 

Structural directives alter layout by adding, removing, and replacing elements in the DOM. The commonly used directives in Angular are *ngIf and *ngFor. 

You can add or remove an element from the DOM by applying an NgIf directive to that element The expression associated with the *ngIf is evaluated and the element is displayed only if the expression returns true 

*ngIf 

In the course.component.ts,

We directly assign true and false to *ngIf, the div tag with the value true is displayed and the one with false is not.

This can be done using a variable in the course.component.ts file.

And in course.component.html

And the output will be:

“All Courses” will not be displayed if showHeading = false 

*ngIf is also used to check for nulls. We now add a class called Course and initialize it as null. We attempt to display its contents in html, but check for null. If the variable “course” is null, the values are not displayed.

In html,

The output will be

But if we initialize the object like this:

The course Object is not null anymore, and will be displayed

*ngFor 

NgFor is a repeater directive — a way to present a list of items. We define a block of HTML that defines how a single item should be displayed. We then tell Angular to use that block as a template for rendering each item in the list. 

<div *ngFor="let course of courses">{{course.name}}</div> 

We initialize an array, courses in course.component.ts and use the ngFor in the course.component.html

In html.

And the output will be

In summary, we looked at *ngFor and *ngIf and how they can be used to dynamically alter the DOM to conditionally display elements and to loop through a list, respectively. 

Services

  • A service contains any value, function, or feature that an app needs. 
  • A service is a class with a narrow, well-defined purpose.  
  • A component's function is to enable the user experience 
  • A component delegates certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console. 
  • You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances. 
  • You can inject a service into a component, giving the component access to that service class. 
  • The @Injectable() decorator is used to provide the metadata that allows Angular to inject it into a component as a dependency. 

A service can be generated using the CLI by typing ng generate service <ServiceName> or in short, ng g s <service name>

2 files are generated, one is the service file and the other is the test class.

In the service file, note the @Injectable annotation. This makes the service available across the application

We now define the course array in the service rather than the component. This can be replaced by a HTTP call to an API

In the course component.ts, the Service is injected via the constructor. The array defined in the service is now assigned to a local variable and the same is referenced in the *ngFor in the HTML

In summary, this is how dependency injection is done in Angular. A service is defined using the @Injectable annotation and its members are made available across the application. 

Data Binding 

  • Data binding is a mechanism for coordinating what users see, with application data values.  

Property Binding

  • Bindings between binding sources (variables) and target HTML elements are declared. Angular does the rest of the work.  
  • Property binding is done using square brackets [] 
<img [src]="heroImageUrl"> 
<button [disabled]="isUnchanged">Cancel is disabled</button>
  • Property binding is a one-way data binding because it flows a value in one direction, from a component's data property into a target element property. 
  • A property binding cannot be used to pull data from an element. It can only be used to set it. 
  • An element property between enclosing square brackets identifies the target property. 
  • Values can be passed into a component using property binding 

There is a variable called user in app.component.ts. It is passed to the course.component using [] as follows: 

App.component.ts

App.component.html

Course.component.ts
The input decorator is used to access input parameters

Course.component.html

And the output will be

We have passed the name “Max” from the variable ”user” in app.component.ts  to course.component.ts using input binding. 

Event Binding

  • User actions may result in a flow of data in the opposite direction: from an element to a component. 
  • Events include being able to listen for certain events such as keystrokes, mouse movements, clicks, and touches.  
  • The target event name is represented within parentheses on the left of an equal sign, and a quoted template statement on the right.  

<button (click)="onSave()">Save</button> 

  • The event in this case is (click) and the method to be called in the component is onSave() 

In course.component.html we add a button for the user to express interest. Note that the course name is passed as parameter to the function “expressInterest”

We then add the method to display an alert message when the button is clicked

Note that we have used a template expression within back-ticks.  
On clicking the button the message is displayed

We used brackets () to bind a user event to a function in the component.  

Examples of events supported by Angular are
Mouse events are (click), (mouseover), (mousedown), (mouseenter), (mouseup), (drag), (dragover)  and (dblclick)
Keyboard events are (keydown), (keypress), (keyup), (copy), (paste), (cut) 

Two-way binding 

  • Two way binding is done using ngModel. This is used to bind user elements like text boxes and dropdowns to variables in the component. 
  • This will allow you to display, listen, and extract at the same time. 
  • ngModel is the easiest way to interact with form elements 

In course.component.ts, add a textbox to take user input of comments

This is bound to a variable called comment in course.component.ts

Summary 

This was a brief introduction to Angular.We covered: 

  1. How to create a new Angular app 
  2. The structure of the Angular app 
  3. The application shell and the root component 
  4. The relationship between the component, template and CSS 
  5. The root module and its structure 
  6. Services and how they are injected into components 
  7. Data binding - property binding, event binding, two-way binding 

This knowledge of Angular is intended to be a springboard into getting started with Ionic.  

Leave a Reply

Your email address will not be published. Required fields are marked *