Angular 6 by Example - Chandermani Arora - E-Book

Angular 6 by Example E-Book

Chandermani Arora

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Harness the power of Angular Components, Router, Forms, Directives and much more to build professional-grade web apps with TypeScript


Key FeaturesGet to grips with #1 JavaScript framework and explore modern concepts for developing single page applicationsDevelop full-featured web applications using Angular 6 and TypeScript from scratchLearn professional web programming techniques to supercharge your Angular projectsBook Description


Angular helps you build faster, more efficient, and more flexible cross-platform applications. Creating complex and rich web applications, with a lighter resource footprint, has never been easier or faster. Angular is now at release 6, with significant changes compared to previous versions.


In this third edition of Angular by Example, you’ll build three apps with varying degrees of complexity. The book starts with a simple Guess the Number game, which serves as a platform to launch you into the world of Angular. Next, you will learn to develop a popular 7-Minute Workout app, covering the building blocks of Angular. The final app, “Personal Trainer” morphs the existing 7-Minute Workout into a full-fledged personal workout builder and runner, covering advanced directive building, which is the most fundamental and powerful feature of Angular. In addition to this, you will learn about testability and the framework constructs Angular provides to effectively test your app. The book concludes by providing you with practical advice and useful tips that will come in handy as you build more apps with Angular.


What you will learnGet introduced to the Angular framework and create a simple guess the number app that explores core features of the framework Dig deeper into the angular framework by building the 7-minute workout app throughout the bookExplore primary building blocks of Angular – components Go deep into the inner workings of Angular 6 directives and componentsLearn about cross-component communication using Angular eventsGet started with the unit and E2E testingUnderstand how to encounter scenarios such as authentication and authorization, localization, performance, and migrating apps from Angular 1 to Angular 6Who this book is for


Angular by Example is an essential guide for beginners who want to get started with Angular. You’ll start building applications immediately with the featured examples and uncover a simpler approach to JavaScript web development. Prior experience with HTML, CSS, and JavaScript is necessary.


Chandermani Arora is a software craftsman, with love for technology and expertise on web stack. With years of experience, he has architected, designed, and developed various solutions for Microsoft platforms. He has been building apps on Angular 1 since its early days. Having a passion for the framework every project of his has an Angular footprint. He tries to support the platform in every possible way by writing blogs on various Angular topics or helping fellow developers on StackOverflow, where he is an active member on the Angular channel. He also authored the first edition of this book. Kevin Hennessy is a Senior Software Engineer with Applied Information Sciences. He has 20 years' experience as a developer, team lead, and solutions architect, working on web-based projects, primarily using the Microsoft technology stack. Over the last several years, he has presented and written about single-page applications and JavaScript frameworks, including Knockout, Meteor, and Angular. He has spoken about Angular at the All Things Open conference.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 622

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Angular 6 by ExampleThird Edition

 

 

 

 

Get up and running with Angular by building modern real-world web apps

 

 

 

 

 

 

 

Chandermani Arora
Kevin Hennessy

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Angular 6 by Example Third Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor:Amarabha BanerjeeAcquisition Editor:Larissa PintoContent Development Editor:Onkar WaniTechnical Editor:Akhil NairCopy Editor:Safis EditingProject Coordinator:Devanshi DoshiProofreader: Safis EditingIndexer:Rekha NairGraphics:Jason MonteiroProduction Coordinator:Nilesh Mohite

First published: October 2016 Second edition: October 2017 Third edition: June 2018

Production reference: 1190618

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78883-517-6

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the authors

Chandermani Arora is a software craftsman, with love for technology and expertise on web stack. With years of experience, he has architected, designed, and developed various solutions for Microsoft platforms. He has been building apps on Angular 1 since its early days. Having a passion for the framework every project of his has an Angular footprint.

He tries to support the platform in every possible way by writing blogs on various Angular topics or helping fellow developers on StackOverflow, where he is an active member on the Angular channel. He also authored the first edition of this book.

Writing this book has just been a surreal experience and I would like to thank everyone on the Packt team including the reviewers who have helped me with this book.I also want to express my gratitude towards my wife, my daughter and everyone else in my family. I am blessed to have you all in my life.

 

 

 

 

Kevin Hennessy is a Senior Software Engineer with Applied Information Sciences. He has 20 years' experience as a developer, team lead, and solutions architect, working on web-based projects, primarily using the Microsoft technology stack. Over the last several years, he has presented and written about single-page applications and JavaScript frameworks, including Knockout, Meteor, and Angular. He has spoken about Angular at the All Things Open conference.

I would like to thank my wife, Mary Gene Hennessy. Her unstinting love and support (and editorial suggestions) through the time that I spent writing this book, have made me ever more aware and appreciate how truly amazing it is to be married to her. I also want to thank my son, Aidan, who has informally tested the code in this book. He is a recent college graduate and his enthusiasm for technology has inspired me in writing this book.

About the reviewer

Phodal Huang is a developer, creator, and author. He works in ThoughtWorks as a Senior Consultant, and focuses on IoT and frontend. He is the author of Design IoT System and Growth: Thinking in Full Stack in Chinese.

He is an open source enthusiast, and has created a series of projects in GitHub. After daily work, he likes to reinvent some wheels for fun. He created the micro-frontend framework Mooa for Angular. You can find out more wheels on his GitHub page, /phodal.

He loves designing, writing, hacking, traveling, you can also find out more about him on his personal website at phodal(dot)com.

 

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Angular 6 by Example Third Edition

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the authors

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Getting Started

Angular basics

The component pattern

Using the component pattern in web applications

Why weren't components used before in Angular?

What's new that enables Angular to use the component pattern?

Web Components

Angular and Web Components

Language support in Angular

ES2015

TypeScript

Putting it all together

Angular modules

The basic steps to building Angular applications

The customary Hello Angular app – Guess the Number!

Building Guess the Number!

Designing our first component

Developing our first component

Installing Bootstrap

What do we have so far?

The host file - index.html

Custom element

The component file

The import statement

Decorator

Defining the class

The module file

Bootstrapping

We're up and running!

Digging deeper

Interpolation

Tracking changes in the number of tries

Expressions

The safe navigation operator

Data binding

Property binding

Event binding

Structural directives

Revisiting our app

Looking at how our code handles updates

Maintaining state

Component as the container for state

Change detection

Tools

Resources

Summary

Building Our First App – 7 Minute Workout

What is 7 Minute Workout?

Downloading the code base

Setting up the build

Angular CLI

Code transpiling

Organizing code

Feature folders

The 7 Minute Workout model

First feature module

App bootstrapping

Exploring Angular modules

Comprehending Angular modules

Our first component - WorkoutRunnerComponent

Component lifecycle hooks

Building the 7 Minute Workout view

The Angular binding infrastructure

Interpolations

Property binding

Property versus attribute

Property binding continued...

Interpolation syntactic sugar over property binding

Quick expression evaluation

Side effect-free binding expressions

Angular directives

Target selection for binding

Attribute binding

Style and class binding

Attribute directives

Styling HTML with ngClass and ngStyle

Learning more about an exercise

Adding descriptions and video panels

Component with inputs

Structural directives

The ever-so-useful NgForOf

Asterisk (*) in structural directives

NgForOf performance

Angular security

Trusting safe content

OnChange life cycle event

Formatting exercise steps with innerHTML binding

Displaying the remaining workout duration using pipes

Angular pipes

Pipe chaining

Implementing a custom pipe - SecondsToTimePipe

Adding the next exercise indicator using ngIf

Pausing an exercise

The Angular event binding infrastructure

Event bubbling

Event binding an $event object

Two-way binding with ngModel

Summary

More Angular – SPA and Routing

Exploring Single Page Application capabilities

The Angular SPA infrastructure

Angular routing

Angular router

Routing setup

Adding start and finish pages

Route configuration

Pushstate API and server-side url-rewrites

Rendering component views with router-outlet

Route navigation

The link parameter array

Using the router service for component navigation

Using the ActivatedRoute service to access route params

Angular dependency Injection

Dependency injection 101

Exploring dependency injection in Angular

Tracking workout history

Building the workout-history-tracker service

Integrating with WorkoutRunnerComponent

Injecting dependencies with Constructor Injection

Dependency injection in depth

Registering dependencies

Angular providers

Value providers

Factory providers

Explicit injection using injector

Dependency tokens

Using InjectionToken

Using string tokens

Adding the workout history page

Sorting and filtering history data using pipes

The orderBy pipe

Pipe chaining with search pipe

Pipe gotcha with arrays

Angular change detection overview

Hierarchical injectors

Registering component-level dependencies

Angular DI dependency walk

 Dependency injection with @Injectable

Tracking route changes using the router service

Fixing the video playback experience

Using thumbnails for video

Using the ngx-modialog library

Creating custom dialogs

Cross-component communication using Angular events

Tracking exercise progress with audio

Building Angular directives to wrap HTML audio

Creating WorkoutAudioComponent for audio support

Understanding template reference variables

Template variable assignment

Using the @ViewChild decorator

The @ViewChildren decorator

Integrating WorkoutAudioComponent

Exposing WorkoutRunnerComponent events

The @Output decorator

Eventing with EventEmitter

Raising events from WorkoutRunnerComponent

Component communication patterns

Injecting a parent component into a child component

Using component life cycle events

Sibling component interaction using events and template variables

Summary

Personal Trainer

The Personal Trainer app - the problem scope

Personal Trainer requirements

The Personal Trainer model

Getting started with the code for Personal Trainer

Using the Personal Trainer model in Workout Builder services

The Personal Trainer layout

Personal Trainer navigation with routes

Getting started with Personal Trainer navigation

Introducing child routes to Workout Builder

Adding the child routing component

Updating the WorkoutBuilder component

Updating the Workout Builder module

Updating App Routing module

Putting it all together

Lazy loading of routes

Integrating sub- and side-level navigation

Sub-level navigation

Side navigation

Implementing workout and exercise lists

WorkoutService as a workout and exercise repository

Workout and exercise list components

Workout and exercise list views

Workouts list views

Exercises list views

Building a workout

Finishing left nav

Adding WorkoutBuilderService

Adding exercises using ExerciseNav

Implementing the Workout component

Route parameters

Route guards

Implementing the resolve route guard

Implementing the Workout component continued...

Implementing the Workout template

Angular forms

Template-driven and reactive forms

Template-driven forms

Getting started

Using NgForm

ngModel

Using ngModel with input and textarea

Using ngModel with select

Angular validation

ngModel

The Angular model state

Angular CSS classes

Workout validation

Displaying appropriate validation messages

Adding more validation

Managing multiple validation messages

Custom validation messages for an exercise

Saving the workout

More on NgForm

Fixing the saving of forms and validation messages

Reactive forms

Getting started with reactive forms

Using the FormBuilder API

Adding the form model to our HTML view

Adding form controls to our form inputs

Adding validation

Adding dynamic form controls

Saving the form

Custom validators

Integrating a custom validator into our forms

Configuration options for running validation

Summary

Supporting Server Data Persistence

Angular and server interactions

Setting up the persistence store

Seeding the database

The basics of the HTTPClient module

Personal Trainer and server integration

Loading exercise and workout data

Loading exercise and workout lists from a server

Adding the HTTPClient module and RxJS to our project

Updating workout-service to use the HTTPClient module and RxJS

Modifying getWorkouts() to use the HTTPClient module

Updating the workout/exercise list pages

Mapping server data to application models

Loading exercise and workout data from the server

Fixing the builder services

Updating the resolvers

Fixing the Workout and Exercise components

Performing CRUD on exercises/workouts

Creating a new workout

Updating a workout

Deleting a workout

Fixing the upstream code

Using promises for HTTP requests

The async pipe

Cross-domain access and Angular

Using JSONP to make cross-domain requests

Cross-origin resource sharing

Handling workouts not found

Fixing the 7 Minute Workout app

Summary

Angular Directives in Depth

Classifying directives

Components

Attribute directives

Structural directives

Building a remote validator directive

Validating workout names using async validators

Building a busy indicator directive

Injecting optional dependencies with the @Optional decorator

Implementation one – using renderer

Angular renderer, the translation layer

Host binding in directives

Property binding using @HostBinding

Attribute binding

Event binding

Implementation two - BusyIndicatorDirective with host bindings

Directive injection

Injecting directives defined on the same element

Injecting directive dependency from the parent

Injecting a child directive (or directives)

Injecting descendant directive(s)

Building an Ajax button component

Transcluding external components/elements into a component

Content children and view children

Injecting view children using @ViewChild and @ViewChildren

Tracking injected dependencies with QueryList

Injecting content children using @ContentChild and @ContentChildren

Dependency injection using viewProvider

Understanding structural directives

TemplateRef

ViewContainerRef

Component styling and view encapsulation

Overview of Shadow DOM

Shadow DOM and Angular components

Summary

Testing Personal Trainer

The need for automation

Testing in Angular

Types of testing

Testing – who does it and when?

The Angular testing ecosystem

Getting started with unit testing

Setting up Karma and Jasmine for unit testing

Organization and naming of our test files

Unit-testing Angular applications

Unit-testing pipes

Running our test files

Unit-testing components

Angular testing utilities

Managing dependencies in our tests

Unit-testing WorkoutRunnerComponent

Setting up component dependencies

Mocking dependencies - workout history tracker

Mocking dependencies – workout service

Mocking dependencies - router

Configuring our test using TestBed

Starting unit testing

Debugging unit tests in Karma

Unit-testing WorkoutRunner continued...

Using Jasmine spies to verify method invocations

Using Jasmine spies to verify dependencies

Testing event emitters

Testing interval and timeout implementations

Testing workout pause and resume

Unit-testing services

Mocking HTTP request/response with HttpTestingController

Unit-testing directives

The TestBed class

Testing remote validator

Getting started with E2E testing

Introducting Protractor

Setting up Protractor for E2E testing

Writing E2E tests for the app

Setting up backend data for E2E testing

More E2E tests

Testing Workout Runner

Using page objects to manage E2E testing

Summary

Some Practical Scenarios

Building a new app

Seed projects

Angular performance

Byte size

Initial load time and memory utilization

The Angular rendering engine

Server-side rendering

Offloading work to a web worker

Performant mobile experience

Change detection improvements

Change detection

Change detection setup

When does change detection kick in?

How does change detection work?

Change detection performance

Using immutable data structures

Using Observables

Manual change detection

Handling authentication and authorization

Cookie-based authentication

Token-based authentication

Handling authorization

Adding authorization support

Sharing user authentication context

Restricting routes

Conditionally rendering content based on roles

Migrating AngularJS apps

Should I migrate?

Advantages of Angular

Developing AngularJS apps today for easy migration

One component per file

Avoiding inline anonymous functions

Avoiding $scope!

Using controller as (controller aliasing) syntax everywhere

Avoiding ng-controller

Building using the AngularJS 1.5+ component API

What to migrate?

Preparing for Angular migration

Identifying third-party dependencies

jQuery libraries

AngularJS libraries

Choice of language

Migrating AngularJS's Personal Trainer

Setting up AngularJS's Personal Trainer locally

Identifying dependencies

Setting up the module loader

Enabling TypeScript

Adding Angular

The ngUpgrade Library

Bootstrapping the hybrid app

Injecting Angular components into AngularJS views

Migrating our first view to Angular component

Injecting AngularJS dependencies into Angular

Registering Angular components as directives

Rules of engagement

AngularJS directives and Angular components

Resource sharing and dependency injection

Sharing an AngularJS service

Sharing an Angular service

Change detection

Migrating the start and finish pages

AngularJS directive upgrade

Replacing angular-translate with ngx-translate

Using ngDoBootstrap for initialization

Integrating the start and finish pages

Getting rid of angular-translate

Learning

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Angular 6 is here, and we are super excited! This book allows us to reach out to you and lend a helping hand in your quest to learn Angular. Angular has gone mainstream and has become the ubiquitous platform for web and mobile development.

If you are an AngularJS developer, then there is loads of exciting stuff to learn, and there is a whole new world to explore for developers getting started. Getting started with Angular can be overwhelming even for a seasoned AngularJS developer. Too many terms will be thrown at you: such as TypeScript, Transpiler, Shim, Observable, Immutable, Modules, Exports, Decorators, Components, Web Component, and Shadow DOM. Relax! We are trying to embrace the modern web, and everything new that is here is to make our lives easier. Lots of these concepts are not specific to Angular itself but highlight the direction in which the web platform development is moving. We will try our best to present these concepts in a clear and concise manner, helping everyone understand how these pieces fit into this big ecosystem. Learning by examples has its advantages, for example, you will immediately get to see the concept explained in action. This book follows the same pattern as its predecessor. Using the Do It Yourself (DIY) approach, we build multiple simple and complex applications using Angular.

Who this book is for

Angular helps you build faster, more efficient, and more flexible cross-platform applications. Angular is now at release 6, with significant changes through its previous versions. This is a unique web development book that will help you get to grips with Angular and explore a powerful solution for developing single page applications.

What this book covers

Chapter 1, Getting Started, introduces you to the Angular framework. We create a super simple app in Angular that highlights some core features of the framework.

Chapter 2, Building Our First App – 7 Minute Workout, teaches us how to build our first real Angular app. In the process, we will learn more about one of the primary building blocks of Angular, components. We will also be introduced to Angular’s templating constructs, databinding capabilities, and services.

Chapter 3, More Angular – SPA and Routing, covers the routing constructs in the framework where we build multiple pages for 7 Minute Workout. This chapter also explores a number of patterns around inter-component communication.

Chapter 4, Personal Trainer, introduces a new exercise where we morph the 7 Minute workout into a generic Personal Trainer app. This app has the capability to create new workout plans other than the original 7 minute workout. This chapter covers Angular’s form capabilities and how we can use them to build custom workouts.

Chapter 5, Supporting Server Data Persistence, deals with saving and retrieving workout data from the server. We augment Personal Trainer with persistence capabilities as we explore Angular's http client library and how it uses RxJS Observables.

Chapter 6, Angular Directives in Depth, goes deep into the inner workings of Angular directives and components. We build a number of directives to support Personal Trainer.

Chapter 7, Testing Personal Trainer, introduces you to the testing world in Angular. You build a suite of unit and end-to-end tests that verify the working of Personal Trainer.

Chapter 8, Some Practical Scenarios, provides some practical tips and guidance around scenarios that we might encounter while developing apps on this framework. We cover scenarios such as authentication and authorization, performance, and the most important case, migrating apps from AngularJS to the latest version of Angular.

To get the most out of this book

We will be building our apps in the TypeScript language; therefore, it would be preferable if you have an IDE that makes development with TypeScript easy. IDEs such as Atom, Sublime, WebStorm, and Visual Studio (or VS Code) are great tools for this purpose.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/chandermani/angular6byexample. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Getting Started

Developing applications in JavaScript is always a challenge. Due to its malleable nature and lack of type checking, building a decent-sized application in JavaScript is difficult. Moreover, we use JavaScript for all types of processes, such as user interface (UI) manipulation, client-server interaction, and business processing/validations. As a result, we end up with spaghetti code that is difficult to maintain and test.

Libraries such as jQuery do a great job of taking care of various browser quirks and providing constructs that can lead to an overall reduction in the lines of code. However, these libraries lack any structural guidance that can help us when the code-base  /grows.

In recent years, JavaScript frameworks have emerged to manage this complexity. Many of these frameworks, including earlier versions of Angular, use a design pattern called Model-View-Controller to separate the elements of the application into more manageable pieces. The success of these frameworks and their popularity in the developer community have established the value of using this pattern.

Web development, however, is constantly evolving and has changed a lot since Angular was first introduced in 2009. Technologies such as Web Components, the new version of JavaScript (ES2015), and TypeScript have all emerged. Taken together, they offer the opportunity to build a new, forward-looking framework. And with this new framework comes a new design pattern—the component pattern.

This chapter is dedicated to understanding the component pattern and how to put it into practice as we build a simple app using Angular.

The topics that we will cover in this chapter are as follows:

Angular basics

: We will briefly talk about the component pattern that is used to build Angular applications

Building our first Angular app

: We will build a small game—

Guess the Number!—

in Angular

An introduction to some Angular constructs

: We will review some of the constructs that are used in Angular, such as interpolation, expressions, and the data binding syntax

Change detection

: We will discuss how change detection is managed in an Angular app

Tools and resources

: Lastly, we will provide some resources and tools that will come in handy during Angular development and debugging

Angular basics

Let's get started by looking at how Angular implements the component pattern.

The component pattern

Angular applications use the component pattern. You may not have heard of this pattern, but it is all around us. It is used not only in software development but also in manufacturing, construction, and other fields. Put simply, it involves combining smaller, discrete building blocks into larger finished products. For example, a battery is a component of an automobile.

In software development, components are logical units that can be combined into larger applications. Components tend to have internal logic and properties that are shielded or hidden from the larger application. The larger application then consumes these building-blocks through specific gateways, called interfaces, which expose only what is needed to make use of the component. In this way, the component's internal logic can be modified without affecting the larger application, as long as the interfaces are not changed.

Getting back to our battery example, the car consumes the battery through a series of connectors. If the battery dies, however, it can be replaced by an entirely new battery, as long as that battery has the same connectors. This means that the builder of the car does not have to worry about the internals of the battery, which simplifies the process of building the car. Even more importantly, the car owner does not have to replace their car every time the battery dies.

To extend the analogy, manufacturers of batteries can market them for a range of different vehicles, for example, ATVs, boats, or snowmobiles. So the component pattern enables them to realize even greater economies of scale.

Using the component pattern in web applications

As web applications continue to become more sophisticated, the need to be able to construct them out of smaller and discrete components becomes more compelling. Components allow applications to be built in a way that prevents them from becoming messes of spaghetti code. Instead, component-based design allows us to reason about specific parts of the application in isolation from the other parts, and then we can stitch the application together into a finished, whole through agreed-upon points of connection.

Also, maintenance costs are less because each component's internal logic can be managed separately without affecting the other parts of the application. And putting applications together using self-describing components makes the application easier to understand at a higher level of abstraction.

Why weren't components used before in Angular?

If this idea makes so much sense, why was the component pattern not adopted in earlier versions of Angular? The answer is that the technologies that existed when Angular was first released did not fully support the implementation of this pattern in web applications.

Earlier versions of Angular, however, made substantial steps in the direction of enabling more intelligent web application design and organization. For example, they implemented the MVC pattern, which separates an application into a model, view, and controller (you will see the use of the MVC pattern continuing within the components that we will build in Angular).

With the MVC pattern, the model is the data, the view is a web page (or a mobile app screen or even a Flash page), and the controller populates the view with data from the model. In this way, separation of concerns is achieved. Following this pattern along with an intelligent use of directives will get you pretty close to components.

So, the earlier versions of Angular allowed applications to be designed and built more logically. However, this approach was limited by the fact that the technologies used were not truly isolated. Instead, they all ended up being rendered without any true separation from other elements on the screen.

What's new that enables Angular to use the component pattern?

By contrast, the newest version of Angular embraces recently emerging technologies, which make it possible to implement the component pattern more fully. These technologies include Web Components, ES2015 (the new version of JavaScript), and TypeScript. Let's discuss what each of these technologies brings to the mix that makes this possible.

Web Components

Web Components is an umbrella term that actually covers four emerging standards for web browsers:

Custom elements

Shadow DOM

Templates

HTML imports

More information on Web Components can be found at https://www.webcomponents.org/introduction

Let's now discuss each of these in detail:

Custom elements

enable new types of DOM elements to be created other than the standard HTML tags such as

<div>

and

<p>

.  You will see the use of these custom elements throughout this book. For example, the application that we are building in this chapter will have a root element named

<app-root>

, but you can give this element any name you like.  Individual components will also use custom elements. For example, in the following chapters we are building a more sophisticated application that breaks the screen down into components. The header of the page will use a custom element

<abe-header>

  to display its content (the prefix

abe

is unique to our application and helps to avoid naming collisions with native HTML elements or custom elements in other apps). The ability to add custom tags provides a location on the screen that can be reserved for binding a component. In short, this is the first step towards separating a component from the rest of the page and making it possible to become truly self-contained.

Shadow DOM

provides a hidden area on the page for scripts, CSS, and HTML. Markup and styles that are within this hidden area will not affect the rest of the page, and equally importantly they will not be affected by the markup and styles on other parts of the page. Our component can use this hidden area to render its display. So, this is the second step in making our component self-contained.

Templates

are fragments of HTML that do not initially render in a web page, but can be activated at runtime using JavaScript. Many JavaScript frameworks already support some form of templating. Web Components standardize this templating and provide direct support for it in the browser. Templates can be used to make the HTML and CSS inside the Shadow DOM used by our component dynamic. So, this is the third step in making our component.

The final standard that makes up Web Components is

HTML imports

. They provide a way to load resources such as HTML, CSS, and JavaScript in a single bundle. Angular does not use HTML imports. Instead, it relies on JavaScript module loading, which we will discuss a little later in this chapter.

Angular and Web Components

Web Components are not fully supported in current web browsers. For that reason, Angular components are not strictly Web Components. It is probably more accurate to say that Angular components implement the design principles behind Web Components. They also make it possible to build components that can run in today's browsers.

At the time of writing, Angular supports evergreen browsers, such as Chrome, Firefox, Safari, and Edge, as well as IE 9 and above. It also has support for Android and IOS. For a list of browsers supported by Angular, visit https://angular.io/guide/browser-support.

Therefore, throughout the rest of this book, we will focus on building Angular components and not Web Components. Despite this distinction, Angular components align closely with Web Components and can even inter-operate with them. As browsers begin to support Web Components more fully, the differences between Angular components and Web Components will begin to disappear. So, if you want to begin adopting the Web Component standards of the future, Angular provides you with the opportunity to do so today.

Language support in Angular

You can develop components with ES5 (the version of JavaScript supported in all current browsers), but Angular enhances the ability to develop components by adding support for key features that are found in the latest languages, such as ES2015 and TypeScript.

ES2015

ES2015 is the new version of JavaScript; it was approved in June 2015. It adds many improvements to the language, which we will see throughout this book, but the two that interest us the most at this point are the following:

Classes

Module loading

Classes did not previously exist in JavaScript. The key advantage of using them, now that they do exist, is that they offer a simple, clear syntax that we can use to create convenient containers for the code in our components. As you will find when you begin working on the applications in this book. Classes also provide a convenient shorthand designation for our components that makes it easier to stitch them together with each other through things such as dependency injection.

To be clear, JavaScript classes do not introduce something that is completely new. The Mozilla Developer Network (MDN) describes them as primarily syntactical sugar over JavaScript's existing prototype-based inheritance.  For more information visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes.

We'll explore classes throughout the examples in this book. If you have not worked with object-oriented languages, you may not be familiar with classes, so we will cover them as we work through the examples in this chapter.

ES2015 also introduces a new approach to module loading. A module provides a way for JavaScript files to be encapsulated. When they are encapsulated, they do not pollute the global namespace and can interact with other modules in a controlled manner. 

Once we have our modules defined, we need a way to load them into our application for execution. Module loading allows us to select just what we need for our application from the modules that make up Angular and other components that we create or use.

Currently, a range of approaches and libraries exists to support module loading in JavaScript. ES2015 adds a new, consistent syntax for loading modules as part of the language. The syntax is straightforward and involves prefixing modules with the export keyword (or using the default export) and then using import to consume them elsewhere in our application.

ES 2015 module loading enables us to combine components into useful bundles or features that can be imported or exported within our applications. In fact, modules are at the core of Angular itself. We will see that modules are used extensively both in Angular itself and in the applications that we are building throughout this book.

It is important to understand that, while Angular uses syntax that has similarities to ES2015 module-loading syntax, Angular modules (which we will discuss a little later in this chapter) are not the same as JavaScript modules. For further details on these differences, see the Angular documentation at https://angular.io/guide/architecture#ngmodules-vs-javascript-modules. 

Because ES2015 is not fully supported by today's browsers, we will need to convert ES2015 into ES5 in order to use features such as classes and module loading in our applications. We do this through a process called transpilation.

Transpilation is like compilation, except that instead of converting our code into a machine language as compilation does, transpilation converts one type of source code to another type of source code. In this case, it converts ES2015 to ES5. There are several tools called transpilers that enable us to do that. Common transpilers include Traceur and Babel. TypeScript (which we will discuss next) is also a transpiler, and it is the one that we will use for the examples in this book.

Once ES2015 is transpiled to ES5, we can then use a module loader such as SystemJS to load our modules. SystemJS follows the ES2015 syntax for module loading and gives us the ability to do module loading in today's browsers. Alternatively, we can  use a module bundler such as webpack to load and combine our modules. For the projects in this book we will be using webpack to load, bundle, and deploy the modules in our applications.

Since the release of ES2015, the schedule for releases of new versions of ECMAScript (the official name for JavaScript) is on an annual basis—so we now have ES2016 and ES2017 and will soon have ES2018.  Since the features that we are highlighting throughout this book were first introduced in ES2015, we will be referring to ES2015 instead of any of the newer versions. The newer versions, however, are fully compatible with the language features that we are highlighting here and elsewhere in the book.

TypeScript

TypeScript was created by Microsoft as a superset of JavaScript, which means that it contains the features of ES2015 (such as classes and module loading) and adds the following:

Types

Decorators

Types allow us to mark variables, properties, and parameters in our classes to indicate that they are numbers, strings, Booleans, or various structures such as arrays and objects. This enables us to perform type checking at design time to make sure that the proper types are being used in our application.

Decorators are simple annotations that we can add to our classes using the @ symbol along with a function. They provide instructions (called metadata) for the use of our classes. In the case of Angular, decorators allow us to identify our classes as Angular components. Decorators also enable us to specify a custom element to which to bind our component and to identify a template that adds an HTML view to our component. We will cover much more about the use of decorators as we go through this book.

Decorators  are not part of ES2015, but are part of a proposal to include them in the JavaScript language in the future. They were added to TypeScript as part of a collaboration between Microsoft and Google. As mentioned earlier, TypeScript compiles into ES5, so we are able to use both types and decorators in browsers that do not fully support ES2015 or the proposed standard for decorators.

As mentioned previously, it is not necessary to use either ES2015 or TypeScript with Angular. However, we think that you will see the advantages of using them as we work through the examples in this book.

Putting it all together

By following the Web Component standards and adding support for ES2015 and TypeScript, Angular gives us the ability to create web applications that implement the component design pattern. These components help realize the vision behind the standards of building large-scale applications through collections of self-describing and self-contained building blocks.

We hope that you will see in the examples in this book that Angular enables components to be constructed in a straightforward and declarative way that makes it easier for developers to implement them. As we proceed through the examples in this book, we will highlight where each of these technologies is being used.

Angular modules

Components are the basic building block of an Angular application. But how do we then organize these building blocks into complete applications? Angular modules provide the answer to this question. They enable us to combine our components into reusable groups of functionality that can be exported and imported throughout our application. For example, in a more sophisticated application we would want to have modules for things such as authentication, common utilities, and external service calls. At the same time, modules enable us to group features within an application in a way that allows us to load them on demand. This is called lazy loading, a topic that we will cover in Chapter 4, Building Personal Trainer.

Each Angular application will have one or more modules that contain its components. Angular has introduced NgModule as a way to conveniently specify the components that make up a module. Every Angular application must have at least one of these modules—the root module.

Angular itself is built as modules that we import into our application. So you will see the use of modules all over as you build Angular apps.

The basic steps to building Angular applications

To sum up: at a basic level, you will see that to develop applications in Angular, you will do the following:

Create components

Bundle them into modules

Bootstrap your application

The best way to understand Angular and the component design pattern is by seeing it in action. Hence, we are going to build our first Hello World app in Angular. This app will help you become familiar with the Angular framework and see the component design pattern in action.

Let's get started doing that.

The customary Hello Angular app – Guess the Number!

As our first exercise, we want to keep things simple, but still showcase the framework's capabilities. Therefore, we are going to build a very simple game called Guess the Number!. The objective of the game is to guess a random computer-generated number in as few tries as possible.

This is how the game looks:

Let's now build Guess the Number!.

Building Guess the Number!

The standard practice while building user interfaces is to build them top-down. Start by designing the UI and then plug in the data and behavior according to your needs. With such an approach, the UI, data, and behavioral aspects of the app are all tightly coupled, which is a less than ideal situation!

With component-based design, we work differently. We start by looking at the UI and expected behavior, and then we encapsulate all of this into a building block that we call a component. This component is then hosted on our page. Within the component, we separate the UI into a view and the behavior into a class, with the appropriate properties and methods needed to support the behavior. If you are not familiar with classes, don't worry. We'll be discussing what they are in detail as we move through the example.

Okay, so let's identify the UI and behavior that we will need for our application.

Designing our first component

To determine what needs to go into our component, we will start by detailing the features that we want the app to support:

Generating random numbers (

original

)

Providing input for a user to guess the value (

guess

)

Tracking the number of guesses already made (

noOfTries

)

Giving the user hints to improve their guess based on their input (

deviation

)

Giving a success message if the user guesses the number correctly (

deviation

)

Now that we have our features, we can determine what we need to display to the user and what data we need to track. For the preceding feature set, the elements in parentheses denote the properties that will support those features and will need to be included in our component.

Designing the component is a very crucial process. If it is done right, we can logically organize our application in a way that makes it understandable and easy to maintain.

While building any app, we urge you to first think about the functionality you want to offer, and then the data and behavior that can support the functionality. Lastly, think about how to build a user interface for it. This is a good practice irrespective of the library or framework that you use to build your app.

Developing our first component

Now that we have a design for our first component, we’ll start developing it using the Angular Command Line Interface (Angular CLI). The Angular CLI enables us to start building Angular applications and deploying them through a series of console commands. We’ll be covering the Angular CLI in greater detail in future chapters. For now, we will install it and use it to generate a basic application as the beginning point for our first component.

To use the Angular CLI you must first install Node.js and npm (Node's package manager). Node is available cross-platform and you can download it from http://nodejs.org. Installing Node also installs npm. For this book, we are using Node.js version 8.9.4 and npm version 5.6.0. You can find more information about installing Node and updating npm to the latest version at https://docs.npmjs.com/getting-started/installing-node.  

Once Node and npm are installed, open a Command Prompt and type the following:

npm install -g @angular/cli

This installs the Angular CLI that we will use to start building our application. Now from a directory on your local machine, enter the following commands:

ng new guessthenumber --inlineTemplatecd guessthenumberng serve

With the first command the Angular CLI will create a new Angular project on your local machine (the --inlineTemplate flag creates a template within our component, which is perfect for what we want to show in this chapter). With the second command, you are navigating to the directory that the Angular CLI has created for your new project. The third command launches the application, which you can view at http://localhost:4200/. If you do that you should see a standard default Angular page in the browser.

Installing Bootstrap

There is one more step before we build out the specifics of our application. Let’s add the Bootstrap library to enhance the look and feel of our application. First, stop the application by typing Ctrl + C in the Terminal from which it was launched and enter Y when asked if you want to terminate the batch job. Next from the guessthenumber directory, enter the following command:

npm install bootstrap --save

This will install the latest release of Bootstrap (which at the time of writing was version 4.0.0). You may see a few warning messages about unmet dependencies. You can ignore them.

Next configure your new project to include the Bootstrap style sheet:

In the

guessthenumber

directory find and open the file

angular.json

In that file find the

projects

property, which contains the settings in our new project

Then find the

styles

property within

architect.build.options

and you will see that it contains an array that holds

styles.css

, the default style sheet for our new project

Add to that array the location of the

bootstrap.min.css

 style sheet like so:

"styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css"],

These instructions for including Bootstrap using the Angular CLI can be found at https://github.com/angular/angular-cli/wiki/stories-include-bootstrap.

What do we have so far?

If you take a look in the guessthenumber directory that the Angular CLI has been created, you will see a large number of files. This may look overwhelming at first, but the important thing to understand is that the Angular CLI has generated all these files for us withjust a few command line statements. In that way it makes getting started with an Angular application much smoother and easier. It takes the grunt work out of the process and enables us able to build and serve our application with minimal effort. In this chapter, we will be focusing on just a few files that we will need to touch in order to create our application.

If you are running the application in Internet Explorer, there is one file that you will need to look at—polyfill.ts. This adds various other files that are needed to run the application in Internet Explorer. You will need to uncomment several sections in that file to add these necessary files. Instructions for doing this are contained in the file itself.

Before turning to building out the specifics of our application, let's take a look at one of the key files that will be used to get our application up and running.

Downloading the example code

The code in this book is available on GitHub at https://github.com/chandermani/angular6byexample. It is organized in checkpoints that allow you to follow along step by step as we build our sample projects in this book. The branch to download for this chapter is GitHub's Branch: checkpoint1.1. Look in the guessthenumber folder for the code we are covering here. If you are not using Git, download the snapshot of Checkpoint 1.1 (a ZIP file) from the following GitHub location: https://github.com/chandermani/angular6byexample/tree/checkpoint1.1. Refer to the readme.md file in the guessthenumber folder when setting up the snapshot for the first time.

The host file - index.html

Navigate to the src folder in the guessthenumber directory and open index.html. You will see the following: 

<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>Guessthenumber</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>

index.html is the host file for our application. It will be launched by the browser when the application is first run and will host the components in our application. If you have any exposure to web development, most of the HTML code in this file should look familiar . It has standard html, head, and body tags along with a couple of optional tags, one a meta tag for the viewport, which configures how the app will display in a mobile device, and the other a link to an Angular favicon image that will display on the tab in the browser in which the application is loaded.

Custom element

However, there is one more important tag on the page that may not look as familiar to you:

<app-root></app-root>

This tag is a custom element. It instructs Angular where to inject the component that we will be building.

Guess the Number! and all the other apps that are part of this book have been tested against the Angular 6 final release.

The component file

Now let's turn to building out the specifics of our application. Given the previous discussion of the component pattern, you will not be surprised that to do this we will be constructing a component.  In this case our application will be simple enough that we will need only one component (later in this book you will see the use of multiple components as we build more complex applications). The Angular CLI has already given us a start by generating a component file for us. Of course, that file does not contain any of the particulars of our application, so we will have to modify it. To do that navigate to the src folder in the app directory and open app.component.ts.

The import statement

At the top of the page, you will find the following line:

import { Component } from '@angular/core';

This is an import statement. It tells us what modules we will be loading and using in our component. In this case, we are selecting one module that we need to load from Angular: Component. Angular has many other modules, but we load only what we need.

You'll notice that the location from which we are importing is not identified as a path or directory within our application. Instead, it is identified as @angular/core. Angular has been divided into barrel modules that are prefixed with @angular.

These barrels combine several modules that are logically related. In this case, we are indicating that we want to import the core barrel module, which in turn brings in the Component module. 

The Angular documentation describes a barrel as:A way to roll up exports from several ES2015 modules into a single convenient ES2015 module. The barrel itself is an ES2015 module file that re-exports selected exports of other ES2015 modules. For more information about barrels, see https://angular.io/guide/glossary#barrel.

The module file

As we mentioned earlier, every Angular component must be contained within an Angular module. This means that at a minimum we must add at least one Angular module file to the root of our application. We call this the root module