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)

First component – NewsComponent

Components are the building blocks of the Angular application. Each component represents some functionality of the application which, when combined with other components, provides a rich user experience. Angular components consist of four parts:

  • Template
  • Class, which is written in TypeScript
  • Metadata, which tells Angular about the class
  • Import statements, which provide reference to other components and services of the application

The following is a graphical representation of the composition of a component:

Template

The template provides the user interface of the component. It's created in HTML and details the elements that are represented in that component. The template for the component can be defined either inline, or in a separate file. We can create an inline template in two ways:

  • We can use a template property in the @Component decorator and define the HTML in single or double quotes. We will read about the @Component decorator in the next chapter. The following is a code example of an inline template:
template: "<h1>{{article.title}}</h1>"
  • If the HTML is more than a couple of lines long, then we can use ES2015 backticks to define the HTML in multiline. There is no difference between either of these ways, apart from readability. Defining inline templates with backticks allows us to create multiline strings, which are more readable:
template: `
<li>
<div>
{{article.description}}
</div>
</li>`

With our view and logic in one file, in one place, it helps to keep track of our bindings with the HTML properties. But, if our HTML is longer than a few lines, then the inline template may not provide many advantages. The inline template is a string, and hence we do not get any IntelliSense support for the HTML tags and syntax checking. The bigger our HTML, the more challenging it becomes to define inline templates.

In these cases, it's better to define the HTML in the separate HTML file and have it linked to the component using the templateUrl property. In the templateUrl property, we define the path of our HTML file, which is relative to index.html. The following is an example of the templateUrl property:

templateUrl: './news.component.html'

Component class

The component class is where the brain of the component resides. This class is written in TypeScript, and has properties and methods. The properties define the data members of the component, and are bound to the template using Angular binding syntax. The methods provide interface for the events that are triggered on the user interface.

As we have learned, each class is defined by the class keyword followed by the class name. One of the best practices defined for the component class is to name the class followed by the component keyword, such as newsComponent. The export keyword in front of the class allows the class to be available to the other components of the application. The following is an example of one such class:

export class itemComponent{
item: string;
itemCount: number;
constructor(){
console.log('Constructor called');
}
printItemDetail(){
console.log('${this.item} has total ${this.itemCount}
copies'
);
}
}

Metadata of the component

The definition of metadata is information about the data, which means when we provide details of the data we use, those details are called metadata. For Angular to understand that the class defined is a component, we need to provide metadata, which in this case would be the information to Angular informing it what the class is about. The metadata also provides Angular with details such as the template for that component, CSS styles for the HTML, and the selector that would be used to represent the component.

The metadata is defined using a decorator on top of the class. The decorator is a JavaScript concept that is proposed for ES7 and is implemented in TypeScript. You can identify the decorator by looking for the @ sign. The component decorator is defined by Angular and has options that allow providing details about the component. Some of the frequently used options are the following:

  • Template/templateUrl: As we discussed in the previous section, this property allows us to define the template for the component.
  • Selector: This defines the component's directive name; using this name, Angular identifies the HTML to be loaded.
  • StyleUrl: This property helps us to define the path of the CSS file for that component. As is the case with the template, we can define CSS either inline or in a separate file.

The following is a code sample for the metadata:

@Component({
s
elector: 'snc-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})

To refer to this component in any other HTML file, we will use the selector property as an HTML tag.

Import

In most cases, the components you are going to create will refer to some external function, or a class. This class can be another component, a model that defines the custom data type, or even a third-party library. To be able to access these functions, we need to import them in our component. Angular allows such imports by using the import keyword.

The import keyword is similar to the using statement we have in C# language. This helps us to access the external methods and properties. One import statement that you will have in your component class would be from Angular. We import the component keyword from the Angular core module, which is used as a decorator in our class. The following is the syntax of the import keyword:

import { Component, OnInit } from '@angular/core'

The import syntax requires that the members we need should be defined in curly braces, followed by the path of the module that contains that member. In the above case, we are importing component and OnInit members from Angular core module.

newsComponent

For our SNC application, we will be creating our first component named newsComponent. The purpose of this component will be to display the latest news from the news source. When we launch our application, this will be the main component that will be loaded. For this chapter, as we decided, we will just have a basic component with some hardcoded data, hence we will just add a few lines of news articles and display them on the user interface.

Angular CLI provides us with the command to generate components for our application. It not only generates the barebone class for the component, but also the external template, and adds the reference to the component in the app module. The syntax of generating a new component is as follows:

ng generate  component <<componentname>>

The following screenshot shows the command we execute for our newsComponent, which generates the required files. We will be creating our component in a dashboard folder under the app folder:

Here, we mentioned that our component is a news component under the dashboard folder, and Angular CLI created three files. Angular CLI creates a folder for the component with the component name, news in our case, to make sure we have separation of concern.

The flag spec false informs Angular CLI not to create the spec files for test cases. By default, Angular CLI, when generating the component or service or pipes, will create an additional file for writing test cases. We will be looking at how to write test cases in an Angular application in Chapter 8, Trello – Using Angular CLI.

You will have noticed here that there is an update to the app.module file as well. This file defines all the components that are under the app module. We will discuss modules in more detail in the following chapter; here, we just want to understand that each component that is created needs to be a reference in the module file. Angular uses this module file to identify which components are associated, and load them appropriately.

Now let's add some code in our newly created component.

newsComponent business logic

Our news component will be very simple and will have the following logic in it:

  1. We will first import the reference to our models, namely News and Article:
import {News} from '../../../models/news';
import {Article} from '../../../models/article';
  1. Then we will create an object of our News model inside the newComponent class:
latest_news: News = new News();

We will have a private method in our class, which will seed our news object. This method will just create some hardcoded objects, which we will display on the screen:

private seedNewsData(): News{
let news:News= new News();
news.status = "ok";
news.source="nfl";
news.sortBy="top";
news.articles = this.seedArcticles();
return news;
}
private seedArcticles():Article[]{
let articles:Article[] = new Array();
articles.push({
......
return articles;
}

This private method will be called from the ngOnInit method. The ngOnInit method is one of the life cycle hooks provided by Angular. The life cycle hooks are the methods that are exposed by the Angular for us to add logic to the component load and unload event. The ngOnInit method is exposed from the Angular core module, and in the following code snippet we see how to use this:

ngOnInit() {
this.latest_news = this.seedNewsData();
}
  1. Once we have assigned the news data to the new object, we can then bind this news property to the HTML template for the new component.

newsComponent template logic

You will have noticed that when we created the component from Angular CLI, it created a separate file for the template. We will be using this file to define our HTML for news details and bind the news property which we defined in the component to display the data.

As our news articles are a list, we will be using one of the built-in Angular structural directives, *ngFor. Angular has predefined directives called structural directives, which enable us to change the structure of the HTML at runtime based on the input provided. These directives add power and flexibility to our HTML by providing features such as for loops and if logic. Here, we are using ngFor to loop through our list of news articles and print each article as a separate element. The following is the code where we use ngFor on the news article:

 <li *ngFor="let article of latest_news.articles">

The preceding statement tells Angular to loop through all the articles in the news object and assign each article to the variable article defined after the let statement. This allows us to access the article properties by using the dot syntax.

Angular provides interpolation for binding the values of properties from the class to the HTML, by using the syntax of double curly braces {{}}. When Angular finds these double curly braces, it evaluates the expression inside these and displays the result as the value in an HTML element. For example, we have the following HTML in our newComponent file:

<div class="para">
{{article.description}}
</div>

Angular here evaluates the expression article.description and prints the result on the screen. You can find the whole HTML on the GitHub page.

Now, once we have defined our component and its respective HTML, it's time to run our application and see the output.

SNC – running the code

As we discussed before, Angular CLI provides a built-in server that builds the application and hosts it on the local node server. We can now run our application using the same command of npm serve. Once you run this command, navigate to http://localhost:4200 in your browser and it should present you with our first cut of the SNC website, as shown in the following screenshot: