Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Angular
Learning Angular

Learning Angular: A no-nonsense beginner's guide to building web applications with Angular 10 and TypeScript , Third Edition

Arrow left icon
Profile Icon Aristeidis Bampakos Profile Icon Pablo Deeleman
Arrow right icon
$44.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (16 Ratings)
Paperback Sep 2020 430 pages 3rd Edition
eBook
$24.99 $35.99
Paperback
$44.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Aristeidis Bampakos Profile Icon Pablo Deeleman
Arrow right icon
$44.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (16 Ratings)
Paperback Sep 2020 430 pages 3rd Edition
eBook
$24.99 $35.99
Paperback
$44.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$24.99 $35.99
Paperback
$44.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning Angular

Chapter 1: Building Your First Angular App

To better understand how to develop an Angular application, we need to learn some basic but essential things so that we can have a great experience on our journey with the Angular framework. One of the basic things that we should know is semantic versioning, which is the way that the Angular team has chosen to deal with changes between different versions of the framework. It will hopefully make it easier to find the right solutions to future app development challenges when you visit the official Angular documentation website (https://angular.io) or other sites (such as Stack Overflow) to search for solutions.

Another important but sometimes painful topic is that of project setup. It is a necessary evil that needs to be done at the beginning of a project, but getting this right early on can reduce a lot of friction as your application grows. Therefore, a large part of this chapter is dedicated to Angular CLI, a tool developed by the Angular team that provides scaffolding and automation tasks in an Angular app, demystifying the process and enabling you as a developer to save yourself from facing future frustrations and migraines. We will use the Angular CLI to create our first application from scratch, get a feel for the anatomy of an Angular application, and take a sneak peek at how Angular works under the hood.

Working with an Angular project without an Integrated Development Environment (IDE) can be painful. Our favorite code editor can provide us with an agile development workflow that includes TypeScript compilation at runtime, static type checking, and introspection, code completion, and visual assistance for debugging and building our app. We will highlight some popular code editors and take a bird's eye view of how each one of them can assist us when developing Angular applications.

To sum up, here are the main topics that we will explore in this chapter:

  • Semantic versioning, why it matters, and Angular's take on it
  • How to set up an Angular project using Angular CLI 10
  • How to use Angular CLI commands to accomplish certain tasks, such as building and serving an Angular app
  • How to create our first application and begin to understand the core concepts in Angular
  • The available tooling for Angular in popular IDEs

Technical requirements

It's just Angular – introducing semantic versioning

Using semantic versioning is about managing expectations. It's about managing how the user of your application, or library, reacts when a change happens to it. Changes happen for various reasons, either to fix something broken in the code or to add/alter/remove a feature. Authors of frameworks or libraries use a way to convey what impact a particular change has by incrementing the version number of the software in different ways.

A piece of production-ready software traditionally has version 1.0, or 1.0.0 if you want to be more specific.

There are three different levels of change that can happen when updating your software. Either you patch it and effectively correct something, make a minor change that essentially means you add functionality, or make a major change that might completely change how your software works. Let's look at these changes in more detail in the following sections.

Patch change

A patch change means that we increment the rightmost digit by one. Changing software from 1.0.0 to 1.0.1 is a small change, and usually implies a bug fix. As a user of that software, you don't really have to worry; if anything, you should be happy that something is suddenly working better. The point is that you can safely start using 1.0.1.

Minor change

A minor change means that the software version increases from 1.0.0 to 1.1.0. We deal with more severe changes as we increase the middle digit by one. This number should increase when new functionality is added to the software, and it should still be backward compatible with the 1.0.0 version. In this case, it should be safe to start using the 1.1.0 version of the software.

Major change

With a major change, the version number increases from 1.0.0 to 2.0.0. Things might have changed so much that constructs have been renamed or removed. It might not be compatible with earlier versions. Please note that many software authors still ensure that there is decent backward compatibility, but the main point here is that there is no warranty, no contract guaranteeing that it will still work.

What about Angular?

Most people knew the first version of Angular as Angular 1; it later became known as AngularJS, but many still refer to it as Angular 1. It did not use semantic versioning.

Then Angular 2 came along, and in 2016 it reached production readiness. Angular decided to adopt semantic versioning, and this caused a bit of confusion in the developer community, especially when it announced that there would be an Angular 4 and 5 and so on. The Angular team, as well as the network of their Google Developer Experts, started to explain that we should call the latest version of the framework Angular—just Angular. You can argue the wisdom of that decision. Still, the fact remains that the new Angular uses semantic versioning, which means that Angular is the same platform as Angular 2, as well as Angular 10, and so on. Adopting semantic versioning means that you, as a user of the framework, can rely on things working the same way until Angular decides to increase the major version. Even then, it's up to you whether you want to remain on the latest major version or upgrade your existing apps.

Introducing Angular

Angular represents a full rewrite of the AngularJS framework, introducing a brand-new application architecture built entirely from scratch in TypeScript, a strict superset of JavaScript that adds optional static typing and support for interfaces and decorators.

In a nutshell, Angular applications are based on an architecture design that comprises trees of web components interconnected by their particular I/O interface. Under the hood, each component takes advantage of a completely revamped dependency injection mechanism.

To be fair, this is a simplistic description of what Angular really is; however, the simplest project ever made in Angular is formed by these definition traits. We will focus on learning how to build interoperable components and manage dependency injection in the following chapters before moving on to more advanced topics, such as routing, web forms, and HTTP communication. We will not make explicit references to AngularJS throughout the book; it makes no sense to waste time and pages referring to something that does not provide any useful insights on the topic. Besides, we assume that you might not know about Angular 1.x, so such knowledge does not have any value here.

Setting up our workspace with Angular CLI

Setting up a frontend project today is more cumbersome than ever. We used to manually include the necessary JavaScript and CSS files in our HTML. Life used to be simple. Then frontend development became more ambitious: we started splitting up our code into modules and using special tools called preprocessors for both our code and CSS.

All in all, our projects became more complicated, and we started to rely on build systems to bundle our applications. As developers, we are not huge fans of configuration—we want to focus on building awesome apps. Modern browsers, however, do more to support the latest web standards, and some of them have even started to support modules. That said, this is far from being widely supported. In the meantime, we still have to rely on tools for bundling and module support.

Setting up a project with Angular can be tricky. You need to know what libraries to import and ensure that files are processed in the correct order, which leads us to the topic of scaffolding. Scaffolder tools almost become a necessity as complexity grows, but also where every hour counts towards producing business value rather than fighting configuration problems.

The primary motivation behind creating the Angular CLI was to help developers focus on app building, eliminating the boilerplate of configuration. Essentially, with a simple command, you should be able to initialize an application, add new artifacts to it, run tests, and create a production-grade bundle. The Angular CLI supports all of this with the use of special commands.

Prerequisites

Before we begin, we need to make sure that our development environment includes a set of software tools that are essential to the Angular development workflow.

Node.js

Node.js is a JavaScript runtime built on top of Chrome's v8 JavaScript engine. Angular requires a current or LTS version. If you have already installed it, you can run node -v in the command line to check which version you are running. If not, you can get it from https://nodejs.org.

Angular CLI uses Node.js to accomplish specific tasks, such as serving, building, and bundling your application.

Npm

Npm is a software package manager that is included by default in Node.js. You can check this out by running npm -v in the command line. The Angular framework is an ecosystem of various libraries, called packages, that are available in a central place called npm registry. The npm client downloads and installs the libraries that are needed to run your application from the registry.

Git

Git is a client that allows us to connect to distributed version-control systems, such as GitHub, Bitbucket, and GitLab. It is optional from the perspective of the Angular CLI. You should install it in case you want to upload your Angular project in a Git repository, which is something that you might want to do.

Installing Angular CLI

The Angular CLI is part of the Angular ecosystem and is available to download from the npm package registry. Since it is used for creating Angular apps and projects, we need to install it globally in our system. Open a terminal and run the following command:

npm install -g @angular/[email protected]

Important Note

On some Windows systems, you may need to have elevated permissions to do this, in which case you should run your command-line window as an administrator. In Linux/macOS systems, run the command using the sudo keyword: sudo npm install -g @angular/[email protected].

The command that we used to install Angular CLI uses the npm client followed by a set of runtime arguments:

  • install or i: Denotes the installation of a package
  • -g: Denotes that the package will be installed to the system globally
  • @angular/cli: Denotes the name of the package to install
  • @10.0.0: Denotes the version of the package to install

CLI commands

Angular CLI is a command-line interface tool that automates specific tasks during development, such as serving, building, bundling, and testing an Angular project. As the name implies, it uses the command line to invoke the ng executable and run commands using the following syntax:

ng command [options]

Here, command is the name of the command to be executed and [options] denotes additional parameters that can be passed to each command. To view all available commands, you can run the following:

ng help

Some commands can also be invoked using an alias instead of the actual command name. In this book, we revise the most common ones (the alias of each command is shown inside parentheses):

  • new (n): Creates a new Angular application from scratch.
  • build (b): Compiles an Angular application and outputs generated files in a predefined folder.
  • generate (g): Creates new files that comprise an Angular application.
  • serve (s): Builds an Angular application and serves it from a preconfigured web server.
  • test (t): Runs unit tests of an Angular application.
  • deploy: Deploys an Angular application to a web-hosting provider. You can choose from a collection of providers that are included in the Angular CLI.
  • add: Installs a third-party library to an Angular application.
  • update: Updates an Angular application along with its dependencies. Dependencies are libraries, npm packages, that are needed for the Angular application to run.

    Important Note

    A library must be compatible with the Angular CLI that is to be used with add and update commands. The way that a library adds compatibility is out of the scope of this book.

Angular CLI follows the same major version of Angular, as all other packages of the framework do. The version that we use in this book and the accompanying source code is 10. You can check which version you have installed by running ng version or ng v in the command line.

Angular CLI uses modern web techniques to orchestrate an Angular application and provide us with a fantastic development experience. It uses Webpack under the hood, a popular module bundler for modern JavaScript applications. We do not interact directly with Webpack, but through the Angular CLI interface.

Creating a new project

Now that we have prepared our development environment, we can start creating magic by scaffolding our very first Angular application. We use the new command of the Angular CLI and pass the name of the application that we want to create as an option. To do so, go to a folder of your choice and type the following:

ng new my-app

Creating a new Angular application is an easy and straightforward process. The Angular CLI will ask you for some details about the application that you want to create so that it can scaffold the Angular project as best as it can. Initially, it will ask you if you want to include routing in your app.

Would you like to add Angular routing? (y/N)

Routing is related to navigating from one view of your application to another, and it is something that we will learn about later in Chapter 7, Navigate through Components with Routing. For now, answer No to the question and press Enter.

The next question is related to the styling of your application.

Which stylesheet format would you like to use? (Use arrow keys)

It is common to use CSS for styling Angular applications. You can, however, use preprocessors, such as SCSS or Less, that can provide added value to your development workflow. In this book, we work with CSS directly, so you can accept the default choice, CSS, and press Enter.

The process may take some time depending on your internet connection. During this time, Angular CLI will download and install all of the necessary dependencies, as well as create default files for your Angular application. When finished, it will have created a folder called my-app. Navigate to the newly created folder and start your application with the following command:

ng serve

Angular CLI compiles the Angular project and starts a web server that watches for changes in project files. This way, whenever you make a change, the web server rebuilds the project to reflect the new changes.

To preview the application, open your browser and go to http://localhost:4200

Figure 1.1 – Landing page of a new Angular app

Figure 1.1 – Landing page of a new Angular app

When we create a new Angular application from scratch, the Angular CLI displays, by default, a landing page that contains useful links, such as where to look for additional resources and documentation about the Angular framework or the next steps to start building our application. In the next section, we will explore how Angular makes the whole process work and learn how to make a change to this landing page.

Hello Angular

We are about to take the first trembling steps into extending our first Angular application. The Angular CLI has already scaffolded our project, and has thereby carried out a lot of heavy lifting. All we need to do is fire up our favorite IDE and start working with the Angular project. We are going to use Visual Studio Code (VS Code) in this book, but feel free to choose any editor you are comfortable with. VS Code is a very popular IDE in the Angular community because of the powerful tooling that it provides to developers. You will learn more details about IDEs later in the IDEs and plugins section.

The landing page of our application is an Angular component that consists of the following parts:

  • Component class: Contains the presentation logic of the component and handles interaction with its template
  • HTML template: The actual UI of the component that interacts with the component class
  • CSS styles: Specific styles that define the look and feel of the component

We will learn about each of the parts in more detail in Chapter 3, Component Interaction and Inter-Communication. For now, let's venture into customizing some of the aforementioned parts of our landing page:

  1. Open VS Code and select File | Open Folder or just Open for Mac users from the main menu.
  2. Search for the my-app folder and select it. VS Code will load the associated Angular project.
  3. Navigate to the app subfolder of the src folder and select the app.component.ts file. This file is the landing page and the main component of the application.

    Important Note

    An Angular application has at least one main component called AppComponent, as a convention.

  4. Locate the property title and change its value to Hello Angular 10:

    app.component.ts

    import { Component } from ‹@angular/core›;
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'Hello Angular 10';
    }
  5. Save the file and wait for Angular to do its thing. It recompiles the project and refreshes the browser. The landing page should reflect the change that you have just made:
Figure 1.2 – Title of landing page

Figure 1.2 – Title of landing page

Congratulations! You have successfully used the Angular CLI to create an Angular application and interact with a component. What you have just experienced is only the tip of the iceberg. There are so many things that happen under the hood, so let's get started by explaining how Angular worked its way to display the actual page on the browser.

Components

Each web application has a main HTML file. For an Angular application, this is the index.html file that exists inside the src folder:

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width,   initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

When the Angular CLI builds an Angular app, it first parses index.html and starts identifying HTML tag elements inside the body tag. An Angular application is always rendered inside the body tag and comprises a tree of components. When the Angular CLI finds a tag that is not a known HTML element, such as app-root, it starts searching through the components of the application tree. But how does it know which components belong to the app?

Modules

Angular organizes components into self-contained blocks of functionality called modules. An Angular application has at least one main module called AppModule, as a convention:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Angular components should be registered with a module so that they are discoverable by the framework. The declarations property is the place where we define all components that exist inside a module. Failure to add a component in this property will mean that it will not be recognized by the framework, and it will throw errors when we try to use it. We will learn more about modules and their properties later in Chapter 5, Structure an Angular App.

As soon as the application knows about all of the available components that it can search, it needs to identify which element tag belongs to which component. That is, it needs to find a way to match the tag with a component.

Selector

Angular matches HTML tags with components via a selector. It is the name that you give to a component so that it is correctly identified in HTML:

selector: 'app-root'

When Angular finds an unknown element tag in an HTML file, it searches through the selectors of all registered components to check whether there is a match. As soon as it finds a matching selector, it renders the template of the component in place of the element tag. You can think of a selector as an anchor that tells Angular where to render a component.

Template

The HTML content of a component is called the template and is defined in the templateUrl property. It denotes the path of the HTML file of the component relative to the component class file:

templateUrl: './app.component.html'

Angular parses the template of the component and replaces the selector it found with the HTML content of this file.

The template of the component is written in valid HTML syntax and contains standard HTML tag elements, some of them enriched with Angular template syntax. It is the Angular template language that extends HTML and JavaScript and customizes the appearance or adds behavior to existing HTML tag elements. To get a glimpse of the Angular template syntax, in VS Code, select the app.component.html file and go to line 330:

<span>{{ title }} app is running!</span>

The {{ }} syntax is one example of the Angular template language, called interpolation. It reads the title property of the component class, converts its value to text, and renders it on the screen as the following:

Hello Angular 10 app is running

Bootstrapping

You have learned how Angular works under the hood to display a component such as the landing page. But how does it know where to start? What is responsible for booting up the process of rendering a page on the screen? This method is called bootstrapping, and it is defined in the main.ts file inside the src folder:

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
  enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

The starting point of an Angular application is always a module. The main task of the bootstrapping file is to define this module. It calls the bootstrapModule method of browser platform and passes AppModule as the entry point of the application.

Important Note

Angular is a cross-platform framework. It can support different types of platforms, such as browser, server, web worker, and native mobile. In our case, we are using the platformBrowserDynamic to target the browser platform.

By now, you should have a basic understanding of how Angular works and what the basic building blocks of the framework are. As a reader, you had to swallow a lot of information at this point and take our word for it. Don't worry: you will get a chance to get more acquainted with the components and Angular modules in the upcoming chapters. For now, the focus is to get you up and running by giving you a powerful tool in the form of the Angular CLI and show you how just a few steps are needed to render an app to the screen.

IDEs and plugins

An IDE is a term that we use for something more powerful than Notepad or a simple editor. Writing code means that we have different requirements than if we were to write an essay. The editor needs to be able to indicate when we type something wrong, provide us with insights about our code, and preferably give us autocompletion that gives us a list of possible methods once we start typing the first letter. A coding editor can and should be your best friend.

For frontend development, there are a lot of great choices out there, and no environment is better than any other; it all depends on what works best for you. This book uses VS Code because of its popularity among the Angular community and the rich collection of plugins that are available from its marketplace. Let's embark on a journey of discovery so that you can be the judge of what environment will best suit you.

Atom

Developed by GitHub, the highly customizable environment and ease of installation of new packages has turned Atom into the IDE of choice for many people.

To optimize your experience with TypeScript when coding Angular apps, you need to install the Atom TypeScript package either via the Atom Package Manager CLI or by using the built-in package installer. It contains a variety of functionalities, such as automatic code hints, static type checking, code introspection, and automatic build-upon saving, to name a few. On top of these, this package also includes a convenient built-in generator to help you easily configure TypeScript for your project.

Sublime Text

Sublime Text is probably one of the most widespread code editors nowadays, although it has lost some momentum lately with users favoring other rising competitors, such as VS Code. To provide support for TypeScript code editing, you need to install Microsoft's TypeScript plugin, available at https://github.com/Microsoft/TypeScript-Sublime-Plugin. Please refer to this page to learn how to install the plugin and all the shortcuts and key mappings.

Once successfully installed, it only takes you pressing Ctrl + Space bar to display code hints based on type introspection. On top of this, you can trigger the build process and compile source files to JavaScript by hitting the F7 key. Real-time code-error reporting is another fancy functionality that you can enable from the command menu.

WebStorm

WebStorm is an excellent code editor supplied by IntelliJ that is great for coding Angular apps. It comes with built-in support for TypeScript out of the box so that you can start developing Angular components from day one. WebStorm also implements a built-in transpiler with support for file watching, so you can compile your TypeScript code into pure vanilla JavaScript without relying on any third-party plugins.

Visual Studio Code

Visual Studio Code, or VS Code as it is more widely known, is an open source code editor backed by Microsoft that is gaining momentum as a serious contender in the Angular community, mostly because of its robust support for TypeScript out of the box. TypeScript has been, to a great extent, a project driven by Microsoft, so it makes sense that one of its popular editors was conceived with built-in support for this language. It means that all the nice features that we might want are already baked in, including syntax, error highlighting, and automatic builds. Another reason for its broad popularity is the various extensions available in the marketplace that enrich the Angular development workflow. What makes VS Code so great is not only its design and ease of use, but also the access to a ton of plugins, and there are some great ones for Angular development. The most popular are included in the Angular Essentials extension pack. To get it, go through the following steps:

  1. Navigate to the Extensions menu of VS Code.
  2. Search for the Angular Essentials keyword.
  3. Click the Install button of the first entry item:
Figure 1.3 – Angular Essentials

Figure 1.3 – Angular Essentials

Alternatively, you can install it automatically, since it is already included in the repository of this book's source code. When you download the project from GitHub and open it in VS Code, it will prompt you to view and install the recommended extensions:

Figure 1.4 – Recommended extensions prompt

Figure 1.4 – Recommended extensions prompt

Let's now look at some of the extensions that are included in the Angular Essentials extension pack in the following sections.

Angular Language Service

The Angular Language Service extension is developed and maintained by the Angular team and provides code completion, navigation, and error detection inside Angular templates. It is included in the Angular Essentials extension pack, but it is also available for WebStorm and Sublime Text editors as a standalone plugin. It enriches IDEs with the following features:

  • Code completion
  • Go-to definition
  • Quick info
  • AOT diagnostic messages

To get a glimpse of the powerful capabilities of the extension, let's have a look at the code completion feature. Suppose that we want to display a new property called description in the template of AppComponent. We can set this up by going through the following steps:

  1. Define the new property in the component class:
    export class AppComponent {
      title = 'Hello Angular 10';
      description = 'Hello World';
    }
  2. Start typing the name of the property in the template. The Angular Language Service will find it and suggest it for you automatically:
Figure 1.5 – IntelliSense in the template

Figure 1.5 – IntelliSense in the template

The description property is a public property. In public methods and properties, we can omit the keyword public. Take the following phrase:

description = 'Hello World';

This phrase is equivalent to the following:

public description = 'Hello World';

Code completion works only for public properties and methods. If the property had been declared as private description = 'Hello World';, then the Angular Language Service would not have been able to find it.

You may have noticed that as you were typing, a red line appeared instantly underneath the HTML element. This is an effect of the AOT diagnostic messages feature. The Angular Language Service did not recognize the property until you typed it correctly and gave you a proper indication of this lack of recognition. If you hover over the red indication, it displays a complete information message about what went wrong:

Figure 1.6 – Error handling in the template

Figure 1.6 – Error handling in the template

Angular Snippets

The Angular Snippets extension contains a collection of TypeScript and HTML code snippets for various Angular artifacts, such as components. To create the TypeScript class of an Angular component using the extension, go through the following steps:

  1. Open VS Code and select File | New File.
  2. Select File | Save As and give it a proper name with the .ts extension, which is the extension for TypeScript files.
  3. Type a-component inside the file and press Enter.

The extension builds the TypeScript code for you automatically. Change the class name and the selector to something more appropriate, and you are ready to start using it in your project:

import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'selector-name',
    templateUrl: 'name.component.html'
})
export class NameComponent implements OnInit {
    constructor() { }
    ngOnInit() { }
}

All available Angular snippets start with the a- prefix.

Nx Console

Nx Console is an interactive UI for the Angular CLI that aims to assist developers that are not very comfortable with the command-line interface or do not want to use it at all. It works as a wrapper over Angular CLI commands, and it helps developers concentrate on delivering outstanding Angular applications instead of trying to remember the syntax of every CLI command they want to use.

The extension is automatically enabled when you open an Angular CLI project. If you click on the Nx Console menu of VS Code, it displays a list of Angular CLI commands that you can execute:

Figure 1.7 – Nx Console

Figure 1.7 – Nx Console

TSLint

TSLint is a tool that performs static analysis of TypeScript code and enforces readability, maintainability, and error checking by applying a set of rules. These rules are defined in the tslint.json configuration file, which can be found in the root folder of an Angular CLI project. It is maintained by Microsoft and must be installed separately:

Figure 1.8 – TSLint

Figure 1.8 – TSLint

Development teams can significantly benefit from its use, as it can govern the coding style that a team uses internally. Developers of a team can agree on a specific set of rules beforehand. When the coding style of a developer does not respect one of these rules, TSLint displays a warning related to the violation. This method ensures that the application code is written consistently by all members of the team and that onboarding new developers on an Angular project becomes an easy process.

Material icon theme

VS Code has a built-in set of icons that it uses to display different types of files in a project. This extension provides additional icons that conform to the Material Design guidelines by Google; a subset of this collection targets Angular-based artifacts.

Using this extension, you can easily spot the type of Angular files in a project, such as components and modules, and increase developer productivity, especially in large projects with lots of files:

Figure 1.9 – Material icon theme

Figure 1.9 – Material icon theme

Important Note

You need to reload VS Code after this extension is installed for the icon changes to take effect.

EditorConfig

VS Code editor settings, such as indentation or spacing, can be set at a user or project level. EditorConfig can override these settings using a configuration file called .editorconfig, which can be found in the root folder of an Angular CLI project. You can define unique settings in this file to ensure the consistency of the coding style across your team.

Summary

That's it! Your journey to the world of Angular has just begun. Let's recap the features that you have learned so far. We looked at semantic versioning and how modern JavaScript frameworks such as Angular use it. We looked over the brief history of the Angular framework and learned how semantic versioning helps the Angular team to deliver up-to-date high-quality features.

We saw how to set up our working space and where to go to find the tools that we need to bring TypeScript into the game and use the Angular framework in our projects, going through the role of each tool in our application. We introduced the Angular CLI tool, the Swiss Army knife for Angular, that automates specific development tasks, and we used some of the most common commands to scaffold our very first Angular application. We had a glimpse of the structure of an Angular component and learned how to interact with it.

Our first application gave us a basic understanding of how Angular works internally to render our app on a web page. We embarked on our journey, starting with the main HTML file of an Angular application. We saw how Angular parses that file and starts searching the component tree to match HTML elements with component selectors and templates. We learned that components that share similar functionality are grouped into modules and looked at how Angular bootstraps the very first module of the application.

Finally, we met some of the most popular IDEs and learned how they can empower you as a software developer. There are many choices for editors, some of which we have chosen to cover in more detail, such as VS Code. There are also many plugins and snippets that save quite a few keystrokes. At the end of the day, your focus and energy should be spent on solving the problem and structuring your solution, not making your fingers tired. We encourage you to learn more about your editor and its possibilities because this will make you faster and more efficient.

In the next chapter, you will learn all about TypeScript, everything from the basics to the professional level. The chapter will cover what problems can be solved by introducing types, but also the language construct itself. TypeScript, as a superset of JavaScript, contains a lot of powerful concepts and marries well with the Angular framework, as you are about to discover.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn the fundamentals of Angular to build web applications using TypeScript
  • Explore the basics of Angular development, from components and templates to forms and services
  • Discover best practices for building, packaging, and testing Angular applications

Description

Angular, loved by millions of web developers around the world, continues to be one of the top JavaScript frameworks thanks to its regular updates and new features that enable fast, cross-platform, and secure frontend web development. With Angular, you can achieve high performance using the latest web techniques and extensive integration with web tools and integrated development environments (IDEs). Updated to Angular 10, this third edition of the Learning Angular book covers new features and modern web development practices to address the current frontend web development landscape. If you are new to Angular, this book will give you a comprehensive introduction to help you get you up and running in no time. You'll learn how to develop apps by harnessing the power of the Angular command-line interface (CLI), write unit tests, style your apps by following the Material Design guidelines, and finally deploy them to a hosting provider. The book is especially useful for beginners to get to grips with the bare bones of the framework needed to start developing Angular apps. By the end of this book, you’ll not only be able to create Angular applications with TypeScript from scratch but also enhance your coding skills with best practices.

Who is this book for?

The Angular TypeScript book is for JavaScript and full-stack developers who want to enter the world of frontend development with Angular or migrate to the Angular framework to build professional web applications. Familiarity with web and programming concepts will assist with understanding the content covered in the book.

What you will learn

  • Use the Angular CLI to scaffold, build, and deploy a new Angular application
  • Build components, the basic building blocks of an Angular application
  • Discover techniques to make Angular components interact with each other
  • Understand the different types of templates supported by Angular
  • Create HTTP data services to access APIs and provide data to components
  • Enhance your application's UX with Angular Material
  • Apply best practices and coding conventions to your large-scale web development projects
Estimated delivery fee Deliver to Taiwan

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 07, 2020
Length: 430 pages
Edition : 3rd
Language : English
ISBN-13 : 9781839210662
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Taiwan

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Sep 07, 2020
Length: 430 pages
Edition : 3rd
Language : English
ISBN-13 : 9781839210662
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 174.97
Learning Angular
$44.99
Angular for Enterprise-Ready Web Applications
$79.99
Angular Projects
$49.99
Total $ 174.97 Stars icon
Banner background image

Table of Contents

18 Chapters
Section 1: Getting Started with Angular Chevron down icon Chevron up icon
Chapter 1: Building Your First Angular App Chevron down icon Chevron up icon
Chapter 2: Introduction to TypeScript Chevron down icon Chevron up icon
Section 2: Components – the Basic Building Blocks of an Angular App Chevron down icon Chevron up icon
Chapter 3: Component Interaction and Inter-Communication Chevron down icon Chevron up icon
Chapter 4: Enhance Components with Pipes and Directives Chevron down icon Chevron up icon
Chapter 5: Structure an Angular App Chevron down icon Chevron up icon
Chapter 6: Enrich Components with Asynchronous Data Services Chevron down icon Chevron up icon
Section 3: User Experience and Testability Chevron down icon Chevron up icon
Chapter 7: Navigate through Components with Routing Chevron down icon Chevron up icon
Chapter 8: Orchestrating Validation Experiences in Forms Chevron down icon Chevron up icon
Chapter 9: Introduction to Angular Material Chevron down icon Chevron up icon
Chapter 10: Giving Motion to Components with Animations Chevron down icon Chevron up icon
Chapter 11: Unit test an Angular App Chevron down icon Chevron up icon
Section 4: Deployment and Practice Chevron down icon Chevron up icon
Chapter 12: Bringing an Angular App to Production Chevron down icon Chevron up icon
Chapter 13: Develop a Real-World Angular App Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4
(16 Ratings)
5 star 43.8%
4 star 12.5%
3 star 6.3%
2 star 12.5%
1 star 25%
Filter icon Filter
Top Reviews

Filter reviews by




Giorgi Jul 30, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good
Amazon Verified review Amazon
Samuel Stegall Oct 06, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Disclaimer: The publisher asked me to review this book, and gave me a copy to read through. As someone who uses Angular at my job frequently, the opinions on topics included are 100% my own.Overview:This book serves as a good introduction of both Angular and TypeScript. I started using these in January of 2019 and have learned much about these concepts since then. It utilizes some of the information in Angular's Tour of Heroes guide, which is quite useful on its own, but pairs well here.What I Like:The book illustrates concepts that are good to know when developing in Angular. Important features of Angular are discussed and built towards, specifically component input/output, observables, and building and deploying Angular apps to a production environment. Other significant concepts are discussed, including validation, component libraries, animation, and unit testing, which are great to be familiar with when working in a professional capacity.What I Dislike:I would have liked for the real world app in Chapter 13 to be something completely separate from the Tour of Heroes app idea, instead opting for something utilizing a public API to reflect consuming external data. However, this Tour of Heroes app presented at the end of the book is a nice alternative to the Todo App that most frontends opt to implement to demonstrate their functionality.What I Would Like To See:I would like to see a chapter moving forward that discusses some of the Angular 10-specific features, such as the new ng new --strict command, which can be used to optimize your Angular project in terms of runtime complexity and project size. I feel like this is well-warranted given that this book targets Angular 10.Final Thoughts:Overall, I wish I would have had a book like this starting out. In just 430 pages, I would have been able to get up to speed much faster in my first job where I used Angular. I feel like it hits the high points well, and provides you with enough to get started with production work. Once you finish this, you will have the tools you need to seek out that which this book doesn't cover (namely, other component libraries, optional packages, etc.), and should be ready to use Angular in your web workflow. As someone with professional experience with both Angular and React, I personally find myself preferring Angular overall for its well defined validation and unit testing by default, and would recommend this book to anyone getting started with the framework.
Amazon Verified review Amazon
abdosup Dec 07, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
i like it
Amazon Verified review Amazon
Tony Tu Dec 03, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Disclaimer:The publisher invited me to review this book and offered a review copy to me. Here, I promise to be 100% sincere in how I feel about this book both good and less so.Overview:This book is typically useful for any front-end or full stack software engineer who is completely new to the web development or has some JavaScript web development experiences but wishes to jump into the Angular world playing with the typescript.What I Really Enjoy:This book is super friendly to the new Angular learner and it will walk you through the important Angular component and concepts. The book illustrates the basic building blocks and structure of Angular application, and teaches you to create your first angular app from scratch and discuss how to bring a real application to production which is especially useful for the less experienced developers. It also helps you learn how to write the proper unit test for angular components, pipes, routes and services which is also a daily job for angular developers.What I Don't Like:Although Angular Ivy was officially introduced in Angular 9 and this book is targeting Angular 10. But big improvements like Ivy engine, it is still worth spending some pages to discuss, or at least give a brief introduction for this important new feature.There is no discussion about the e2e testing or an introduction to use protractor - the official end to end testing framework for angular apps. Protractor can help run e2e tests like a user in a real browser against your angular application which is very useful as test-driven practice.What I Would Like to See:I would like to see more discussions on recently introduced changes or improvements between Angular release, like Ivy compiler and runtime or the new flag for the strict mode . Angular framework has been through lots of design and technical changes since its beginning , it is easy to disorient the newcomers to the Angular ecosystem. So it's worth spending more ink on it.I also would like a new chapter to contribute to the end to end testing part and present how to setup and use the protractor framework.Overall, just like the subtitle ,this book has no-nonsense. Writing a good book for the beginners never be an easy job but this book is well done for it. It guides you on major angular development topics. I wish I had the same opportunity like the readers of this book when I jumped into the angular world two years ago, it could save me a lot of effort and become more productive in a short time.
Amazon Verified review Amazon
John Giannetti Apr 07, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very clear and to the point. I wish more technical books were written this way.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela