Book Image

TypeScript 2.x By Example

By : Sachin Ohri
Book Image

TypeScript 2.x By Example

By: Sachin Ohri

Overview of this book

The TypeScript language, compiler, and open source development toolset brings JavaScript development up to the enterprise level. It allows you to use ES5, ES6, and ES7 JavaScript language features today, including classes, interfaces, generics, modules, and more. Its simple typing syntax enables building large, robust applications using object-oriented techniques and industry-standard design principles. This book aims at teaching you how to get up and running with TypeScript development in the most practical way possible. Taking you through two exciting projects built from scratch, you will learn the basics of TypeScript, before progressing to functions, generics, promises, and callbacks. Then, you’ll get to implement object-oriented programming as well as optimize your applications with effective memory management. You’ll also learn to test and secure your applications, before deploying them. Starting with a basic SPA built using Angular, you will progress on to building, maybe, a Chat application or a cool application. You’ll also learn how to use NativeScript to build a cool mobile application. Each of these applications with be explained in detail, allowing you to grasp the concepts fast. By the end of this book, you will have not only built two amazing projects but you will also have the skills necessary to take your development to the next level.
Table of Contents (11 chapters)

SNC – 101

It's time to jump in over our heads by building our first application. At the start of the chapter, we briefly discussed what the application is all about and how the finished product will look. We will be building this application gradually, starting in this chapter and then adding features to the application in Chapter 3, Sports News Combinator - Adding Features, and Chapter 4, Sports News Combinator - the Final Version. With each new feature, we will first discuss the feature and then implement it.

SNC is an SPA built with Angular and TypeScript. We will be using Angular 4 as our frontend framework, and all the code written in Angular will be in TypeScript. This book does not assume that the reader is proficient in Angular, and hence we will be explaining Angular concepts as we go along.

In the second-half of this chapter, we will focus on the following items of our SNC application:

  • Introduction to Angular: As our application is built on top of the Angular framework, it makes sense for us to first understand the basics of Angular.
  • First step: To start building the application, the first step is to set up the code structure. We will briefly discuss the multiple ways to set up Angular code; more details will be in Chapter 8, Trello – Using Angular CLI.
  • Building our first component: Once the basic code is set up, we will start developing our application by building our first component.

By the end of this chapter, we will have one simple component to display a list of data with images. We are intentionally not adding many features to our application in this chapter because we would like to have more focus on the concepts of Angular and TypeScript. Once we have our basics clear, it will be very easy to look at other features and implement them in our application.

Angular – the superhero framework

In this book, we will be creating three applications, and all the applications will be built with the Angular and TypeScript framework. So, it makes sense for us to spend some time understanding what Angular is, and its basic concepts.

In this section, we will learn just enough concepts to help us start with our first application. In subsequent chapters, as we add features to our applications, we will look at other features of Angular along with TypeScript in detail.

SPAs

In the last couple of decades, web applications have come a long way, from static web applications to web applications with some JavaScript, to jQuery, where we were building dynamic web applications. As the need for web applications increased, technology also evolved to handle the ever-changing needs. Earlier, it was fine to go to the server for each user request, for each page navigation. But, as the need changed, we were looking for ways to make our web applications more fluid, have shorter load time, and reduce the number of requests to the server.

In came SPAs, which provided just the right concepts to improve application performance. The basic premise of an SPA is to have a single HTML page, and just keep swapping the inner content of HTML as the user interacts with the application rather than always loading a whole new page. This approach lets us reduce the request count, reduce the size of the application, and in turn, increases application responsiveness.

Angular is not the only SPA framework on the market at the moment; there are other frameworks such as React, Aurelia, and Vue, which also try to provide a mechanism to create SPAs, though Angular is the most popular one.

Angular – the concepts

Angular is an open source JavaScript/TypeScript framework for building rich client-side applications. Angular uses HTML, CSS, and TypeScript or JavaScript as its building blocks. If you have used jQuery before and are wondering how Angular differentiates itself from jQuery, then you can look at the features it provides. Angular is a full-fledged web application development, unlike jQuery, which is more of a wrapper for JavaScript functions helping in providing a common API for handling different browsers.

Angular provides features to create HTML pages and embed CSS into them, routing to help navigate between pages, services to provide an interface to interact with the backend, and components to stitch all these together. Angular is an opinionated framework, in the sense that it provides guidance on how we should create web applications.

We can easily build our web applications without using Angular as our framework in just plain JavaScript but, in doing so, we would end up defining all the underlying features that can help develop the application. Angular provides many standout features over creating custom frameworks for web applications, as shown in the following diagram:

  • Adds power to the HTML: Angular provides structural directives, which help add flexibility to HTML. With the help of Angular, we can make our HTML more expressive.
  • Better data binding with models: Angular provides a mechanism to bind data models with UI, and help track changes. It has features such as one-way binding and two-way binding, which allows applications to set up a channel between the models and their respective UI elements.
  • Faster load time: Angular has one of the fastest load times, which allows for better rendering and more fluid applications.
  • Reusability: One of the guiding principles of Angular design is its ability to help create a modular design. Angular is designed in a modular way, wherein each feature of Angular is available as a separate module to help manage the dependencies. Modularity allows building components and features that are reusable.
  • Integrates well with backend systems: Angular has specific functionalities that provide interfaces to help communicate with backend servers.
  • Futureproof: Angular follows all the modern practices. It takes advantage of the latest features in JavaScript and TypeScript such as classes, interfaces, and decorators.
  • Better productivity: With all the features of Angular, you will see the productivity improving exponentially when developing any web application. Angular provides a framework that makes it easy to start and implement features and functionalities.

Angular – the architecture

Angular is a modular framework that provides separation of concerns with regard to features and technology. All Angular features are also managed in separate modules; you have a core module, which is responsible for basic features such as components and NgModule, then there are modules for services, pipes, and internationalization, among others. This provides us with the opportunity to create our applications with Angular in more modular fashion to provide us with reusability and ease of use.

Angular application on a high level is comprised of components and services that help us create features and bind them together to make an application. Multiple components can be clubbed together in a module to provide a functionality. For example, we can have a component for report filter and a component for report result. Both these components can be bound together inside a module. The following figure shows a high-level view of how an Angular application is composed:

Components are further divided into three main parts:

  • HTML, which forms the UI of the component called template. These UI templates form the view of the application. Templates have a 1:1 relationship with the component, and can be defined either inline or in a separate HTML file.
  • A class that is written in TypeScript and contains all the properties and methods that are required by the view. Properties are the data members that are bound to the view and used to display the data. Methods are action events that are performed from the view, such as a button click.
  • Angular needs a way to identify a class defined above as a component so that it can process it to display on the screen. This information is provided to Angular by the form of metadata.

The following is a graphical representation of a component:

This approach of having multiple components to form a module and multiple modules to form an application allows us to have separation of concerns and create multiple reusable components that can be used in different applications.

When we navigate to the URL of an Angular application, the first component that is loaded is always a root application component, and then the Angular router uses the routing configuration defined to match the component with the URL, and loads that component. The components template is then displayed in the browser, with data fetched from the server. A component can be made up of multiple smaller components, which are then loaded subsequently.

SNC – the architecture

Before we start developing our application, it is a good idea to look at the high-level architecture of what we will be building. The architecture provides us with the blueprint for designing our application, which in this case, will define the components that we will be building and their hierarchy. The following is an architecture diagram of SNC:

This application is comprised of the set of components and modules with index.html as our starting point. From index.html, we have an app component, which is the parent component. Then we have two components, namely header and footer, to provide with common content. Our main application is made of one component, news, which provides the primary user interface. We also have a service layer, which is used to make a backend call to fetch the top 10 news stories for a specific channel. The news component will show all the stories in a list format. This is achievable because of the hierarchical setup of components, with news as a parent component and story as a child component. In this chapter, we will keep it simple and develop only one component, which will have the list of stories; we will be adding components and their interaction in Chapter 3, Sports News Combinator - Adding Features, and Chapter 4, Sports News Combinator - the Final Version.

SNC – code setup

Angular provides multiple ways to set up the initial code structure, with options ranging from quick seed project, found at https://github.com/angular/quickstart, to Angular Command Line Interface (Angular CLI), which is an npm package and allows you to create applications that can run immediately. There are also multiple startup projects provided by various Angular enthusiasts, each with something different. Angular is a frontend framework that needs to be hosted on a server to run. It supports various servers such as node, IIS, and even Tomcat.

As we saw earlier, Angular is built with modules, with each module loading different components. Angular supports module loaders such as SystemJS and Webpack. You will find startup projects with either of the module loaders. For our application, we will use Angular CLI to create our initial project structure. We will look at Angular CLI and other startup projects in detail in Chapter 8, Trello – Using Angular CLI; here, just follow the steps we discuss and we should have our application running in no time.

If we had to manually set up a project from scratch, we would have to perform the following steps:

  1. First, we would need to create an application folder, a traditional app folder.
  2. Add package details and other configuration files.
  3. Install these packages using npm.
  4. Then we need to create an Angular root module. As we discussed in the SNC - architecture section, each application has one root module, which is required to load the application.
  1. Create a file called main.ts, which will load the module.
  2. Create an index.html file that will be our one and only fully HTML file.
  3. Develop your first component, which will be called from the app component.
  4. Define Angular routes to help Angular identify which component to load based on the URL request.

As you will notice, there are quite a few steps that need to be performed, and doing these manually is time-consuming and error-prone. This is where Angular CLI comes in. It creates all these files and also some boilerplate code for our first component. Angular CLI also provides commands to create new components/services/pipes/directives, among others. Angular CLI code comes with a built-in server from the Node that helps run the application in the development mode.

The Angular CLI package helps create an initial web application for Angular with Webpack and node server built in. It follows best practices as defined by the official Angular team, and helps to provide us with the correct folder structure to manage the code.

Angular CLI  setup

To start using Angular CLI, you will need to install the Angular CLI package from npm. npm, or Node Package Manager, is a package manager for all the client-side repositories. If you don't have npm and node on your machine, you can install it by downloading the executable from Node's website at https://nodejs.org/en/download/. If you think you already have node and npm, you can check which version you have with the following command executed in the Terminal window:

node -v
npm -v

These commands will give you the version you already have installed on your machine. Before Angular CLI can help you build web applications, you need to install Angular CLI itself from npm with the following command on a Terminal window:

npm install -g angular-cli

This command will install the angular-cli package in your global npm scope.

Application setup

Once we have CLI installed, then we can start creating our application. Creating an application with CLI is as simple as running the following command in your Terminal window:

ng new <<projectname>> 

The project name will be the name you would like to give to your project, which in our case, will be SportsNewsCombinator. The following screenshot shows the executed command and the result:

As you can see in the preceding screenshot, the CLI created a load of files and folders for our project. If you compare the files that we discussed in the previous section when listing down the manual steps to configure a new project, you will find all those here. In addition, there are files for e2e test cases, which we will not focus on at this time. As we discussed earlier, the CLI provides the built-in node server for us to run our application; the following command does that exactly:

ng serve

This command builds the projects and starts the web server. Once this command is executed, we can just navigate to our browser and open the URL http://localhost:4200.

You should see a page similar to the following:

And we are up and running. Though this is nowhere close to how our application will look, this step helps us to start our application.

SNC – folder structure

Angular CLI creates the folder structure, which is one of the recommended ones from the Angular team. Although you can create your own custom folder structure and follow the practices as per your organization, Angular CLI helps to get you started with minimal effort. The following screenshot shows the folder structure that was created for our project:

The following are the folders created by Angular CLI:

  • e2e: This folder is used for creating and managing end-to-end test cases for the application. In this example, we will not focus on writing test cases. We will cover how to write test cases later in the book.
  • node_modules: All the packages that we define in package.json are downloaded by npm under this folder. We never check-in this folder with our code base and always expect users to run npm install to download the packages. If you are downloading this code from GitHub, do remember to run the npm install command.
  • src: All our application code resides in this folder. We have an app folder inside the src, which will have all the application-related files and an assets folder, which will have all external assets such as icons and images.
  • environments: The purpose of this folder is to provide environmental configurations when you are building your application. You may have different configurations for different environments, and this folder helps you manage that.
  • Other files: We have other files in our src folder which are used at startup, such as main.ts, index.html, and tsconfig.app.json. We will look at these files when developing our application.

Now it's time to get our hands dirty.