Book Image

Learning Angular - Third Edition

By : Aristeidis Bampakos, Pablo Deeleman
Book Image

Learning Angular - Third Edition

By: Aristeidis Bampakos, Pablo Deeleman

Overview of 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.
Table of Contents (19 chapters)
1
Section 1: Getting Started with Angular
4
Section 2: Components – the Basic Building Blocks of an Angular App
9
Section 3: User Experience and Testability
15
Section 4: Deployment and Practice

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.