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.
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.
e2e | Contains test cases written using Jasmine |
node_modules | Contains 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 |
src | This folder contains the Angular source code for the project |
Angular.json | Configuration defaults for Angular CLI. Includes configuration for build, serve, test. You will be able to run most projects with default configurations |
.editorconfig | Configurations for code editors. https://editorconfig.org/ |
.gitignore | List of untracked files for git to ignore. |
package-lock.json | Provides version information for all npm packages |
tsconfig.json | Default TypeScript configuration |
tslint.json | Default TSLint configuration for apps in the workspace. |
README.md | Introductory documentation |
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.
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
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
declarations | The components, directives, and pipes that belong to this NgModule. |
exports | The subset of declarations that should be visible and usable in the component templates of other NgModules. |
imports | Other modules whose exported classes are needed by component templates declared in this NgModule. |
providers | Services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. |
bootstrap | The 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.
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
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.
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.
<img [src]="heroImageUrl"> <button [disabled]="isUnchanged">Cancel is disabled</button>
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.
<button (click)="onSave()">Save</button>
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)
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
This was a brief introduction to Angular.We covered:
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 *