Home Web Development Learning Angular - Third Edition

Learning Angular - Third Edition

By Aristeidis Bampakos , Pablo Deeleman
books-svg-icon Book
eBook $35.99 $24.99
Print $44.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $44.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Building Your First Angular App
About this book
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.
Publication date:
September 2020
Publisher
Packt
Pages
430
ISBN
9781839210662

 

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/cli@10.0.0

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/cli@10.0.0.

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.

About the Authors
  • Aristeidis Bampakos

    Aristeidis Bampakos is a Web Development Team Lead at Plex-Earth who specializes in the development of web applications with Angular. He has been an Angular Google Developer Expert (GDE) since 2020 and works as an Angular Senior Tech Instructor at Code.Hub, a private educational institute, where he nurtures aspiring Angular developers and professionals. He is also the author of Angular Projects with Packt.

    Browse publications by this author
  • Pablo Deeleman

    With sound expertise in front-end libraries and frameworks such as Backbone.js, Knockout.js, VueJS, React, Svelte, AngularJs, and Angular, Pablo Deeleman has developed his career since 1998 as a JavaScript engineer across a broad range of successful companies such as Gameloft, Red Hat or Dynatrace, just to name a few. He currently works as Staff Software Engineer at Twilio, the global leader in customer engagement communications. Pablo Deeleman has contributed to the dev community with several books on Angular since 2016, all published by Packt Publishing.

    Browse publications by this author
Latest Reviews (3 reviews total)
Duidelijk boek met oefeningen
No lo he estudiado todavia, pero el temario me parece muy interesante y aporta a los otros libros ya comprados.
Topics well covered. The book is a good start to get started with Angular.
Learning Angular - Third Edition
Unlock this book and the full library FREE for 7 days
Start now