0% found this document useful (0 votes)
303 views

Angular Crash Course-Part 1

This document provides an overview of Angular, a popular JavaScript framework for building single-page web applications. It discusses Typescript, the programming language used by Angular, and how to install Typescript. It then covers Typescript fundamentals like variable declaration, types, arrays, type inference, and type assertion. The document also discusses key object-oriented programming concepts in Typescript like arrow functions, interfaces, classes, objects, constructors, access modifiers, and properties. The goal is to provide readers with an introduction to building simple single-page applications with Angular and Typescript.

Uploaded by

Benjie Lenteria
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
303 views

Angular Crash Course-Part 1

This document provides an overview of Angular, a popular JavaScript framework for building single-page web applications. It discusses Typescript, the programming language used by Angular, and how to install Typescript. It then covers Typescript fundamentals like variable declaration, types, arrays, type inference, and type assertion. The document also discusses key object-oriented programming concepts in Typescript like arrow functions, interfaces, classes, objects, constructors, access modifiers, and properties. The goal is to provide readers with an introduction to building simple single-page applications with Angular and Typescript.

Uploaded by

Benjie Lenteria
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Angular Crash Course

Building Simple Single-Page Applications

By

BENJIE B. LENTERIA
Mater Dei College
Tubigon, Bohol
Introduction
Angular is one of the most popular JavaScript frameworks, that developers use to build dynamic
websites. It is an open-source software engineering framework used for building single-page
web apps. Developers also use it to create animated menus for HTML web pages.
The framework is the brainchild of Google engineers, Misko Hevery and Adam Abrons. Google
officially released the first version, AngularJS, in 2012, and has been maintaining it ever since.

Typescript Fundamentals
Angular framework uses the Typescript programming
language by MicrosoftTM. Typescript is a superset of
Javascript which means that all valid Javascript code is valid
Typescript code. Since modern browsers of today do not
support Typescript, Angular transpiles the Typescript code
into Javascript which is the one being served to the browser
on execution.

Installing Typescript
Before we can use typescript to do any programming tasks, we need to install typescript into our
development system. This is quite easy using the Node Package Manager (npm).
In the next section, we will try to write, compile, and run our first typescript code. For this we will
not be using the browser. Instead, we will run our basic typescript program right in the command
line interface or terminal.

First Typescript Code

The code example above is a simple typescript code as indicated by the filename main.ts but as
you can see, it is just a JavaScript code. Once you compile this file, the typescript compiler will
generate a JavaScript representation of the above typescript program main.js whose content is
obviously the same as the typescript one.

Once we have trans-piled the typescript code into JavaScript, we can now run our JavaScript
program using node.

For the succeeding section in our crash course, we will be focusing on the things that are
unique to typescript. Namely, the features and capabilities of typescript that is missing on the
latest version of JavaScript.
We will learn about Typescript’s variable declaration, Types and Type assertions, Arrow
functions, Interfaces, Class, Objects, Constructors, Access modifiers, Properties and Modules.
These features embody most of the design patterns used in modern programming languages of
today. These programming concepts greatly enhance the development experience and flow into
a more mature way of writing code which are readable, reusable, and testable without
sacrificing robustness and reliability.

Variable Declaration
We know that in JavaScript, we use the keyword var when declaring a variable. The problem
with var keyword is that it declares a variable that is scoped to the nearest function, and not to
the block where the declaration is located. Starting ES6 version of JavaScript, they introduced
the let keyword which declares a variable that is scoped to the exact block where the
declaration is located. However, all browsers only support ES5 JavaScript and not ES6 and
therefore, does not have the let keyword.
Typescript supports both let and var keywords when declaring variables bearing with them of
course its differences in its scope. However, since the typescript code is trans-piled into ES5
JavaScript which is what all browsers support, the let keyword is ultimately converted into var
keyword but with a compilation error regarding variables used not within proper scope.

Variable Types
In Typescript, there are fewer types than most programming languages.

Type Description Values

number For storing numbers both integer and floating point 100,99.9,077,0xFF0

string For storing strings of characters “Something”

boolean For storing true or false True or false

any Basically the same as any JavaScript type Any value

//number
let count = 5;
//string
let name = ‘John’;
//boolean
let isOpen = false;
Array Declaration
//number array
let arr = [1,2,3,4];
//string array
let members = [“Ariel”, “James”, “Henry”];

//any array
let all = [1, 2.0, “Rank”, true];

Type Inference
In a simple variable declaration and initialization (as shown above), Typescript performs type
inference. That is, it will automatically decide the type of the variable based on the value that is
initialized on it. However, for situations where there is not initialization, the type that will be
inferred to it is any.

Declaring Variables With Data Type


For instances where variables are not initialized but require to be of a specific type rather than
any, you can declare it with a type declaration.

//number
let count: number;
//string
let name: string;
//boolean
let success: boolean;
//array
let scores: number[];
let names: string[];
let responses: boolean[];

Type Assertion
Sometimes a variable is declared as any. Somewhere along the execution, you need to access
some features specific to a particular type such as strings or other objects for that matter. In
these situations, you can use type assertions wherein you can temporarily assert a particular
type to a variable (usually of type any) and consequently be able to access the features specific
to that type that you asserted.
let something;
something = "Some text";
//apply string type assertion to access string features
//extract a substring from something
let substring = (<string>something).substring(0,5);
//another way of type assertion
let substring2 = (something as string).substring(0,5);
console.log(substring, substring2);

Arrow Functions
Another concept that you need to know when building an Angular application using Typescript is
the concept of Arrow functions. In Java and C# this concept is called a Lambda Expression.
//JavaScript function
var log = function(message) {
console.log(message);
}
//Typescript Arrow function
let log = (message) => {
console.log(message);
}

Interfaces
The concept of interfaces is very common among Object-Oriented programming such as Java,
C#, and many other programming languages. It's a very effective programming concept that
allows programmers to provide rule sets for invoking functions thereby preventing programmers
from wrongfully invoking functions with invalid sets of arguments.
Classes
In the previous section, we use an interface to define the shape of an object. However,
interfaces only binds a contract to the one using it. Interfaces do not have definitions of actual
methods. Using interfaces and creating other methods that use the interface violates the
concept of cohesion. In computer programming, cohesion refers to the degree to which the
elements inside a module belong together. In one sense, it is a measure of the strength of the
relationship between the methods and data of a class and some unifying purpose or concept
served by that class. Following the concept of cohesion, all data and actions that are related to
each other should be encapsulated within one unit. The solution to this is to use classes where
we define data and actions within one structure.

Objects
After classes, the obvious thing that should follow is of course Objects. As we all know, Objects
are instances of classes. From a single Class we can instantiate an infinite number of Objects.
Most modern applications are running using a whole slew of these objects interacting with each
other. In Typescript, we can define classes just like any other Object-Oriented programming
languages. This will help us to achieve the concept of cohesion.
Constructors
Just like many Object-Oriented programming languages, Typescript also provides constructors
which allows us to define a way of instantiating objects with field initialization.

With the above constructor defined in the ExamResults class, we can now instantiate an object
with initial values to its fields.
let resultX = new ExamResults(80, 90, 95);
However, unlike Java or C#, Typescript does not allow multiple declarations of a method nor a
constructor. There is a slight difference in the implementation of the concept of Overloading in
Typescript. To implement different sets of parameters for invoking a method or instantiating an
object, you can make some of the parameters optional by adding a question mark (?) at the end
of the parameter name. Note that all the parameters to the right of an optional parameter should
also be optional.
With the constructor above, we can instantiate an ExamResults class one of four ways:
(1)without arguments, (2)with one number argument which will initialize the englishScore field,
(3)with two number arguments which will initialize both englishScore and scienceScore fields,
and (4) with three number arguments which will initialize all of the fields of ExamResults class.

Access Modifiers
Sometimes we have parts of our class that are intended only for internal purposes and should
not be accessed from the outside. Furthermore, there are some fields which need to be
modified in a specific way and therefore should not be modified from the outside as well.
In Object-Oriented programming, we have this concept called Access Modifiers which are
keywords that you can apply to the class members to control its access from the outside.
In Typescript there are 3 Access Modifiers namely: public, private, and protected. The first two
are the most common and if a class member is not given an access modifier, it will be public by
default. You can apply these access modifiers on fields, properties and methods.

Because of the private access modifiers on the fields, these fields are no longer directly
accessible from the outside. As seen below, red squiggly lines indicate compilation errors.
let result2 = new ExamResults();
result2.englishScore = 80;
result2.scienceScore = 90;
result2.generalInfoScore = 95;

Access Modifiers in Constructors


Typescript has a fantastic feature that drastically shortens your code when dealing with fields
and constructor parameters. By simply providing an access modifier on the parameters in the
constructor, Typescript compiler will automatically generate a field of the same name as the
parameter and initialize it with the value of the parameter.
Consider the code below..
class Point {
private x: number;
private y: number;
constructor(x?:number, y?:number) {
this.x = x;
this.y = y;
}
}
The code above can be rewritten into a shorter version using access modifiers in the constructor
parameter. You will see a lot of this in the entire Angular Crash Course.
class Point {
constructor(private x?:number, private y?:number) { }
}

Properties
In some cases, fields and properties are interchangeable concepts. However, in Typescript,
fields and properties are (although similar) different concepts. In the example above, x and y are
both fields. We can convert these fields into properties by giving them either a setter (using the
set keyword) or a getter (using the get keyword) or both. In the example below we will convert
the x and y fields into properties by adding each a getter.

Similarly, you can use a setter to add a functionality that allows programmers to change the
value of a property.
Although properties look just like fields, you are actually invoking methods under the hood to
access and/or change values of the fields.

Modules
In a real-life application, you might have tens, hundreds, or even thousands of classes. You
don’t want to write them all in one file because that would be disastrous to maintain. Instead, we
will write each class in its own file and in most cases, organize these files into folders. In order
for the items from a certain file to be accessed by another file, we need to turn it into a Module.
In simple terms, a module is simply a file that contains classes, functions, properties and fields
which are intended to be shared externally. To turn a file into a module we simply add the
keyword export into the item you want to share externally. The file that will access a module will
subsequently use the import phrase in order to gain access to the shared items of a module.
In the following example, we write our Point class in a separate file and turn it into a module
and then access it from another file.

In the next chapter we will start our lesson with the basics of Angular…
Angular Fundamentals
In this section we will talk about the bits and pieces of things that make up an angular
application. At the end of this section, you should have a basic understanding of the building
blocks of an Angular application such as Components, Templates, Directives and Services.

Building Blocks of Angular Applications

Components
At the heart of an Angular application is one or more components. A real-world application may
contain tens, hundreds of even thousands of components. But what is a component? A
component encapsulates the data, the HTML markup and the logic for the view (the area of the
screen that the user sees). You can divide the whole application into smaller parts and treat
each part as a component. In the heart of the application will be the main component. Inside the
main component are other components representing the specific parts of the application.
Basically, your application will be structured as a tree of components where the main component
is the root.
For example, suppose you have a page in a web application which may contain several areas
such as the navigation bar, the sidebar, and the content. All these can each be a component
under the main component. And even further down the hierarchy, the content component might
contain one or more components.
Generating Components Using Angular CLI
Using the Angular CLI, we can generate a lot of the building blocks of an angular application.
This includes automatic generation of a component by simply issuing the command ng generate
component <name of component>.

In the above example, Angular CLI generated four files and updated the app.module.ts file to
include the newly generated component into its declarations section.

Templates
The previous section talks about the Angular component which encapsulates the data, the
HTML markup and the logic to render the view into the DOM. Templates provide us with
functionality to render data dynamically. The HTML is defined in the component decorator using
either the template property or the templatesUrl property. The latter indicates the path to a
separate file containing the HTML code, while the former will contain the actual HTML code.
Data defined within the component class as well as methods that return values can be accessed
within the HTML template through the use of String interpolation. In the example below the title
data as well as the result of the message() method is being accessed in the HTML template
using String interpolation.

Directives
Directives are perhaps the most important bit of an Angular application, and if we think about it,
the most-used Angular unit, the component, is actually a directive.
An Angular component isn’t more than a directive with a template. When we say that
components are the building blocks of Angular applications, we’re actually saying that directives
are the building blocks of Angular applications.
At the core, a directive is a function that executes whenever the Angular compiler finds it in the
DOM. Angular directives are used to extend the power of the HTML by giving it new syntax.
Each directive has a name — either one from the Angular predefined like ng-repeat, or a
custom one which can be called anything. And each directive determines where it can be used:
in an element, attribute, class or comment.
By default, from Angular versions 2 and onward, Angular directives are separated into three
different types:

Components
As we saw earlier, components are just directives with templates. Under the hood, they use the
directive API and give us a cleaner way to define them.
The other two directive types don’t have templates. Instead, they’re specifically tailored to DOM
manipulation.
Attribute directives
Attribute directives manipulate the DOM by changing its behavior and appearance.
We use attribute directives to apply conditional style to elements, show or hide elements or
dynamically change the behavior of a component according to a changing property.

Structural directives
These are specifically tailored to create and destroy DOM elements.
Some attribute directives — like hidden, which shows or hides an element — basically maintain
the DOM as it is. But the structural Angular directives are much less DOM friendly, as they add
or completely remove elements from the DOM. So, when using these, we have to be extra
careful, since we’re actually changing the HTML structure.
Reference: https://www.sitepoint.com/practical-guide-angular-directives/

Services
Angular services are singleton objects that get instantiated only once during the lifetime of an
application. They contain methods that maintain data throughout the life of an application, i.e.
data does not get refreshed and is available all the time. The main objective of a service is to
organize and share business logic, models, or data and functions with different components of
an Angular application.
An example of when to use services would be to transfer data from one controller to another
custom service.

Why Should We Use Services in Angular?


The separation of concerns is the main reason why Angular services came into existence. An
Angular service is a stateless object and provides some very useful functions. These functions
can be invoked from any component of Angular, like Controllers, Directives, etc. This helps in
dividing the web application into small, different logical units which can be reused.
For example, your controller is responsible for the flow of data and binding the model to view.
An Angular application can have multiple controllers, to fetch data which is required by the
entire application. Making an AJAX call to the server from the controller is redundant, as each
controller will use similar code to make a call for the same data. In such cases, it's extremely
useful to use a service, as we can write a service which contains the code to fetch data from the
server and inject the service into the controller. Services will have functions to make a call. We
can use these functions of services in the controller and make calls to the server, that way we
need not write the same code again and it can be used in components other than controllers as
well. Also, controllers no longer have to perform the task of fetching the data, as services take
care of this, thus achieving the objective of Separation of Concerns.
Reference: https://dzone.com/articles/what-is-a-service-in-angular-js-why-to-use-it

Dependency Injection
Dependency injection (DI), is an important application design pattern. Angular has its own DI
framework, which is typically used in the design of Angular applications to increase their
efficiency and modularity. In Angular, the DI framework provides declared dependencies to a
class when that class is instantiated. Here are the essential concepts in Angular DI:
Dependency: A dependency would be a service, function, object or value that a class needs to
perform its function.
Injector: An injector is responsible for creating dependency instances and injecting them into
classes like components. Angular creates an application-wide injector for you during the
bootstrap process, and additional injectors as needed. You don’t have to create injectors.
Provider: A provider tells an injector how to create the service. You must configure an injector
with a provider before that injector can create a service (or provide any other kind of
dependency).
Here are the steps DI performs behinds the scenes:
Step1: When Angular creates a new instance of a component class, it determines which
services or other dependencies that component needs by looking at the constructor parameter
types.
Step2: When Angular discovers that a component depends on a service, it first checks if the
injector has any existing instances of that service. If a requested service instance doesn’t yet
exist, the injector makes one using the registered provider, and adds it to the injector before
returning the service to Angular. If the component’s injector lacks the provider, it passes the
request up to its parent component’s injector.
Step3: When all requested services have been resolved and returned, Angular can call the
component’s constructor with those services as arguments.

The @Injectable() decorator is an essential ingredient in every Angular service definition. The
class we have created provides a service. The @Injectable()decorator marks it as a service that
can be injected.
Now that our service is an Injectable, we can use this service by injecting it to our component
instead of creating an instance.

Generating Service Using Angular CLI


Like a lot of other things, you can generate a service using the Angular CLI tool. Using this tool,
you will be able to generate a service with just one terminal command.
The above command will generate the file shown below…
Displaying Data & Handling Events
Angular is a front-end framework. A lot of the things it is meant for is dynamically displaying
pieces of information on the screen. In this section we will learn in more detail the techniques for
presenting (showing/hiding) pieces of visual content and all the logic that comes along with it.

Property Binding
Property binding is a technique, which will help to bind values to the properties of DOM
elements. This is done by enclosing the DOM property within HTML with a square bracket and
assigning it with a field from the component class.

Attribute Binding
On rare occasions, you will not be able to access some attributes because they don’t exist in the
DOM but only as an HTML attribute. For such a case you can use Attribute binding. This time,
you will not be binding the value of a component field to a property of a DOM element, but to an
attribute of an HTML element.
Class Binding
You can also engage or disengage a CSS class on an HTML element dynamically based on
truthiness of a component field. In the example below, the CSS class “enabled” is engaged on
the input element because the value of the isEngaged field on the component is true.

Style Binding
You can also control CSS styles in an HTML element or DOM object using Style Binding in
Angular. It is very similar to class binding and just like Class Binding it is also a variation of
property binding.

Event Binding
One very important aspect of any application is to react to specific actions that the user
performed within the application. In Angular, you can define specific actions to perform in
reaction to an event performed by the user within the application. With event binding, you can
attach a function to any known event triggered by any DOM object.

This event object will bubble up the DOM tree unless an event handler along the way prevents
further bubbling. This behaviour is a standard event mechanism in DOM and is nothing specific
to Angular.
To prevent an event object from bubbling up the DOM hierarchy, we can pass a reference of the
event object into the event handler function. The event object can be referenced using $event
keyword. In the event handler we can then call $event.prevenPropagation() to stop the
event bubbling.

Template Variables
In Angular, you can use what is known as Template Variable in order to have a reference of a
DOM element into the component. A Template Variable is defined in the HTML element tag
prefixed by ‘#‘ sign followed by the user-defined reference name. This name can then be
passed to the component through any event binding expression.
Two-way Binding
While Property Binding and Event Binding provide us with nifty possibilities, there comes a time
when you need an extra layer of dynamism. For some situations when you need to have
real-time monitoring and dynamic data exchanges between the template and the component
class, we can use Two-way Binding. With Two-way binding, any changes happening to the
template, is actively reflected to the component and vice-versa.
Two-way binding uses the ngModel directive that serves as a middleman-object to bind a field
from the component class with any DOM element from the template bidirectionally. This
however, is not readily available right off the bat because the ngModel directive is not part of the
core module. In order to user Two-way Binding, we need to import the FormsModule where the
ngModel directive is a part of.

…..

Pipes
Pipes are used to transform your template data into whatever format you desire. Some
examples would be formatting a number into currency, turning texts into uppercase letters,
adding prefixes and suffixes to string and many other possibilities. In angular there are several
built-in pipes that encompasses the most common data transformation requirements. But for
some data transformation that is very specific to the application you are building, you can also
define your own pipes and implement it across your application.
To be continued…..

You might also like