29,99 €
As part of the best-selling *Pocket Primer* series, this book introduces readers to basic machine learning concepts and integrates them into Angular applications. It offers a fast-paced introduction to essential machine learning features and an overview of popular classifiers. Covering Angular functionality, basic machine learning concepts, and key classification algorithms, the book includes numerous code samples and figures. Topics such as TensorFlow and Keras are also explored.
The book begins with a quick introduction to Angular, followed by UI controls, user input, and forms and services. As you progress, you will delve into machine learning, working with classifiers, and integrating TensorFlow.js with Angular. These foundational topics ensure a comprehensive grasp of both Angular and machine learning principles, equipping you with practical skills for developing sophisticated applications.
Understanding these concepts is crucial for enhancing Angular projects with machine learning capabilities. This book transitions you from a novice to a proficient developer, equipped with the knowledge and tools needed to create advanced applications. Companion files with source code and color figures enhance the learning experience, making this book an invaluable resource for integrating machine learning with Angular.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 299
Veröffentlichungsjahr: 2024
ANGULARANDMACHINE LEARNING
Pocket Primer
Oswald Campesato
Copyright ©2020 by MERCURY LEARNING AND INFORMATION LLC. All rights reserved.
This publication, portions of it, or any accompanying software may not be reproduced in any way, stored in a retrieval system of any type, or transmitted by any means, media, electronic display or mechanical display, including, but not limited to, photocopy, recording, Internet postings, or scanning, without prior permission in writing from the publisher.
Publisher: David Pallai MERCURY LEARNING AND INFORMATION 22841 Quicksilver Drive Dulles, VA [email protected] (800) 232-0223
O. Campesato. Angular and Machine Learning Pocket Primer. ISBN: 9781683924708
The publisher recognizes and respects all marks used by companies, manufacturers, and developers as a means to distinguish their products. All brand names and product names mentioned in this book are trademarks or service marks of their respective companies. Any omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to infringe on the property of others.
Library of Congress Control Number: 2020934206
202122 321 Printed on acid-free paper in the United States of America
Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc. For additional information, please contact the Customer Service Dept. at (800) 232-0223(toll free).
Digital versions of our titles are available at: www.academiccourseware.com and other electronic vendors. Companion files are available from the publisher by writing to [email protected].
The sole obligation of MERCURY LEARNING AND INFORMATION to the purchaser is to replace the book and/or disc, based on defective materials or faulty workmanship, but not based on the operation or functionality of the product.
I’d like to dedicate this book to my parents – may this bring joy and happiness into their lives.
CONTENTS
Preface
1 QUICK INTRODUCTION TO ANGULAR
What You Need to Understand for Angular Applications
A High-Level View of Angular
A High-Level View of Angular Applications
The Angular CLI
Features of the Angular CLI (optional)
A “Hello World” Angular Application
The Contents of the Three Main Files
The index.html Web Page
Exporting and Importing Packages and Classes (optional)
Working with Components in Angular
Syntax, Attributes, and Properties in Angular
Angular Lifecycle Methods
A Simple Example of Angular Lifecycle Methods
CSS3 Animation Effects in Angular
Animation Effects via the “Angular Way”
A Basic SVG Example in Angular
Detecting Mouse Positions in Angular Applications
Angular and Follow-the-Mouse in SVG
Angular and SVG Charts
D3 Animation and Angular
Summary
2 UI CONTROLS, USER INPUT, AND PIPES
The ngFor Directive in Angular
Displaying a Button in Angular
Angular and Radio Buttons
Adding Items to a List in Angular
Deleting Items from a List in Angular
Angular Directives and Child Components
The Constructor and Storing State in Angular
Conditional Logic in Angular
Handling User Input
Click Events in Multiple Components
Working with @Input, @Output, and EventEmitter
Presentational Components
Working with Pipes in Angular
Creating a Custom Angular Pipe
Reading JSON Data via an Observable in Angular
Upgrading Code from Earlier Angular Versions
Reading Multiple Files with JSON Data in Angular
Reading CSV Files in Angular
Summary
3 FORMS AND SERVICES
Overview of Angular Forms
An Angular Form Example
Angular Forms with FormBuilder
Angular Reactive Forms
Other Form Features in Angular
What are Angular Services?
An Angular Service Example
A Service with an EventEmitter
Searching for a GitHub User
Other Service-Related Use Cases
Flickr Image Search Using jQuery and Angular
HTTP GET Requests with a Simple Server
HTTP POST Requests with a Simple Server
An SVG Line Plot from Simulated Data in Angular (optional)
Summary
4 INTRO TO MACHINE LEARNING
What is Machine Learning?
Types of Machine Learning Algorithms
Feature Engineering, Selection, and Extraction
Dimensionality Reduction
Working with Datasets
What is Regularization?
The Bias-Variance Tradeoff
Metrics for Measuring Models
Other Useful Statistical Terms
What is Linear Regression?
Other Types of Regression
Working with Lines in the Plane (optional)
Scatter Plots with NumPy and Matplotlib (1)
Scatter Plots with NumPy and Matplotlib (2)
A Quadratic Scatterplot with NumPy and Matplotlib
The Mean Squared Error (MSE) Formula
Calculating the MSE Manually
Approximating Linear Data with np.linspace()
Calculating MSE with np.linspace() API
Linear Regression with Keras
Summary
5 WORKING WITH CLASSIFIERS
What is Classification?
What are Linear Classifiers?
What is kNN?
What are Decision Trees?
What are Random Forests?
What are SVMs?
What is Bayesian Inference?
What is a Bayesian Classifier?
Training Classifiers
Evaluating Classifiers
What are Activation Functions?
Common Activation Functions
The ReLU and ELU Activation Functions
Sigmoid, Softmax, and Hardmax Similarities
Sigmoid, Softmax, and HardMax Differences
What is Logistic Regression?
Keras, Logistic Regression, and Iris Dataset
Summary
6 ANGULAR AND TENSORFLOW.JS
What is TensorFlow.js?
Working with Tensors in TensorFlow.js
Machine Learning APIs in TensorFlow.js
Linear Regression with TensorFlow.js
Angular, TensorFlow.js, and Linear Regression
Creating Line Graphs in tfjs-vis
Creating Bar Charts in tfjs-vis
Creating Scatter Plots in tfjs-vis
Creating Histograms in tfjs-vis
Creating Heat Maps in tfjs-vis
TensorFlow.js, tfjs-vis, and Linear Regression
Summary
INTRODUCTION TO KERAS
INDEX
PREFACE
What is the Goal?
The goal of this book is to introduce advanced beginners to basic machine learning and incorporate that knowledge into Angular 8 applications. This book is intended to be a fast-paced introduction to some basic features of machine learning and an overview of several popular machine learning classifiers. It includes code samples that are part of a university course taught by the author of this book.
This book will save you the time required to search for code samples, which is a potentially time-consuming process. If you’re not sure whether you can absorb the material in this book, glance through the code samples to get a feel for the level of complexity.
At the risk of stating the obvious, please keep in mind the following point: you will not become an expert in machine learning or Angular 8 by reading this book.
What Will I Learn from This Book?
The first three chapters contain a short tour of basic Angular functionality, such as UI components and forms in Angular applications. The fourth chapter introduces you to machine learning concepts, such as supervised and unsupervised learning, followed by the major types of machine learning algorithms (regression, classification, and clustering), along with a section discussing linear regression. The fifth chapter is devoted to classification algorithms, such as kNN, Naïve Bayes, decision trees, random forests, and SVM (Support Vector Machines).
The sixth chapter introduces basic TensorFlow concepts, followed by TensorFlow.js (i.e., TensorFlow in modern browsers) and some examples of Angular applications combined with machine learning. The appendix contains an introduction to Keras, along with some basic code samples.
Although Jupyter is popular, all the code samples in this book are Python scripts. However, you can quickly learn about the useful features of Jupyter through various online tutorials. In addition, it’s worth looking at Google Colaboratory: it is entirely online, is based on Jupyter notebooks, and offers free GPU usage.
How Much Keras Knowledge is Needed for This Book?
Some exposure to Keras is helpful, and you can read the appendix if Keras is new to you. If you also want to learn about Keras and logistic regression, there is an example in Chapter 3. This example requires some theoretical knowledge involving activation functions, optimizers, and cost functions, all of which are discussed in Chapter 4.
Please keep in mind that Keras is well-integrated into TensorFlow 2 (in the tf.keras namespace), and it provides a layer of abstraction over the “pure” TensorFlow that will enable you to develop prototypes more quickly.
Do I Need to Learn the Theory Portions of This Book?
Once again, the answer depends on the extent to which you plan to become involved in machine learning. In addition to creating a model, you will use various algorithms to see which ones provide the level of accuracy (or some other metric) that you need for your project. If you fall short, the theoretical aspects of machine learning can help you perform a “forensic” analysis of your model and your data, and ideally assist in determining how to improve your model.
How Were the Code Samples Created?
The code samples in this book were created and tested using Python 3 and Keras that’s built into TensorFlow 2 on a Macbook Pro with OS X 10.12.6 (macOS Sierra). The code samples were derived primarily from the author for his Deep Learning and Keras graduate course. In some cases, there are code samples that incorporate short sections of code from discussions in online forums. The key point to remember is that the code samples follow the “Four Cs”: they must be Clear, Concise, Complete, and Correct to the extent that it’s possible to do so, given the size of this book.
Launching the Code Samples: Please Read This
Since the code samples require more than 10 GB of disk space, which is greater than the capacity of a DVD, all the node_modules subdirectories have been deleted. Hence, you need to run the following command from the top-level directory of each Angular application:
npm install
The version numbers for the Angular CLI and NodeJs are displayed in the section “Installing the Angular CLI” in Chapter 1, and they are displayed below for your convenience:
Angular CLI: 8.3.21
Node: 13.3.0
OS: darwin x64
Angular:
...
Package
Version
----------------------------------------------------
@angular-devkit/architect
0.803.21
@angular-devkit/core
8.3.21
@angular-devkit/schematics
8.3.21
@schematics/angular
8.3.21
@schematics/update
0.803.21
rxjs
6.4.0
You might have different versions of the Angular CLI and Node, and if they are close to the version numbers displayed above, they will probably work as well.
Another point to keep in mind: several code samples in Chapter 3 were created with an additional manual invocation of npm, which means that the file package.json is slightly different in those directories. Therefore, do not copy package.json from one code sample to other code samples.
In the event that you do overwrite package.json with another copy of this file, the code samples that involve the extra command line invocation will have the following comment in app.component.ts:
// remember: npm install jquery –save
If the file app.component.ts does not have this type of comment line, then you only need to invoke npm install once from the command line.
I Received An Error After Launching npm: What Can I Do?
One potential error that can occur when you launch npm install in the code samples is shown here:
An unhandled exception occurred: Could not find module "@angular-devkit/build-angular"
The first step involves removing the file package-lock.json:
rm package-lock.json
The second step is to install the package (introduced in Angular 6) listed in the preceding error message as a dependency, which involves the following command:
npm install --save-dev @angular-devkit/build-angular
The third step involves the standard npm invocation:
npm install
There are other errors that can occur for various reasons (such as different versions of the Angular CLI), and in those situations, perform an Internet search. There’s a good chance that someone else has encountered the same error and has a solution for that error.
What are the Technical Prerequisites for This Book?
For the machine learning aspect of this book, you need some familiarity with Python, and also know how to launch Python code from the command line (in a Unix-like environment for Mac users). In addition, a mixture of basic linear algebra (vectors and matrices), probability/statistics, (mean, median, and standard deviation) and basic concepts in calculus (such as derivatives) will help you learn the material in this book. Some knowledge of NumPy and Matplotlib is also helpful, and the assumption is that you are familiar with their basic functionalities (such as NumPy arrays).
For the Angular aspect of this book, you need some familiarity with TypeScript as well as RxJS and Observables. Since RxJS is a JavaScript-based implementation of FRP (Functional Reactive Programming), some knowledge of the latter would be very useful.
One other prerequisite is important for understanding the code samples in the second half of this book: some familiarity with neural networks, including the concepts of hidden layers and activation functions (even if you don’t fully understand them). Knowledge of cross entropy is also helpful for some of the code samples.
What are the Non-Technical Prerequisites for This Book?
Although the answer to this question is more difficult to quantify, it’s very important to have strong desire to learn about machine learning, along with the motivation and discipline to read and understand the code samples.
Even simple machine language APIs can be a challenge to understand the first time you encounter them, so be prepared to read the code samples several times.
How Do I Set Up a Command Shell?
If you are a Mac user, there are three ways to do so. The first method is to use Finder to navigate to Applications > Utilities, and then double click on the Utilities application. Next, if you already have a command shell available, you can launch a new command shell by typing the following command:
open /Applications/Utilities/Terminal.app
A second method for Mac users is to open a new command shell on a Macbook from a command shell that is already visible simply by clicking command+n in that command shell, and your Mac will launch another command shell.
If you are a PC user, you can install Cygwin (open source, available at https://cygwin.com/) that simulates bash commands, or use another toolkit such as MKS (a commercial product). Please read the online documentation that describes the download and installation process. Note that custom aliases are not automatically set if they are defined in a file other than the main start-up file (such as .bash_login).
Companion Files
All the code samples and figures in this book may be obtained by writing to the publisher at [email protected].
What are the “Next Steps” After Finishing This Book?
The answer to this question varies widely, mainly because the answer depends heavily on your objectives. If you are interested primarily in Angular, then you can learn more advanced Angular features that you can incorporate in new Angular applications.
If you are primarily interested in machine learning, there are many resources available, and you can perform an Internet search for those resources. The aspects of machine learning for you to learn depend on who you are: the needs of a machine learning engineer, data scientist, manager, student, and software developer are all different.
O. Campesato March 2020
CHAPTER 1
QUICK INTRODUCTION TO ANGULAR
This chapter provides a fast introduction to Angular-based applications. While many of the code samples are straightforward, you need to invest additional time and effort to acquire a deeper understanding of Angular. The purpose of the code samples is to illustrate some fundamental features of Angular. Although some fine-grained details are discussed, you will need to consult some online tutorials to gain a thorough understanding of the features of Angular.
Another important factor is your learning style: you might prefer to read the details regarding the “scaffolding” for Angular applications before you delve into the first code sample. However, it’s perfectly acceptable to skim the introductory portion of this chapter, quickly “get into the weeds” with the Angular sample code, and afterward review the initial portion again.
The first part of this chapter discusses some of the design goals of Angular and its various features, such as components, modules, and one-way data binding. The second part of this chapter discusses the Angular CLI, which is a command-line tool for generating Angular applications.
NOTE The Angular applications in this book are based on Angular 8, using the ng command line utility for creating Angular applications.
There are several points to keep in mind before you read this short book. First, the code samples highlight basic coding techniques in Angular applications. Hence, you will not find an in-depth and highly detailed description of the Angular concepts, design goals, and architecture that are available in 600-page books. However, you can fill some of those technical gaps via online articles.
Second, you can learn the Angular concepts in the various applications without having previous experience with Angular, but obviously some knowledge of Angular would be helpful.
Third, this chapter contains some Angular applications for generating SVG-based graphics and D3-based animation effects. Due to space constraints, this chapter does not contain an introduction to SVG or D3. Fortunately, there are many online tutorials that provide detailed information regarding the features of SVG and D3. If you are not interested in either of these technologies, feel free to skip the associated code samples, since there will be no loss of continuity.
What You Need to Understand for Angular Applications
Two important technologies in Angular are TypeScript and RxJS. In very casual terms, TypeScript might remind you of combining JavaScript with a classical object-oriented approach. If you have an affinity for Java, you will probably be more comfortable with the “look-and-feel” of TypeScript than JavaScript.
RxJS is JavaScript-based FRP (Functional Reactive Programming) that supports many intermediate operators, such as filter(), map(), take(), and other useful operators. The following subsections contain some additional details regarding TypeScript and RxJS.
Learn TypeScript
Knowledge of TypeScript is highly recommended, along with a basic proficiency in NodeJS (i.e., the npm utility) and ES6. The Angular applications have been created with the Angular CLI (discussed later) that uses node v12.6.0 and npm 6.9.0, but it’s likely that slightly lower versions will work as well. Determine the version on your machine with the following commands:
node -v
npm -v
If necessary, navigate to the NodeJS home page to download a more recent version of the node executable. If you have not worked with Node, read an online tutorial to learn how to use basic npm commands.
The code samples include basic concepts about ES6 and TypeScript, and their respective home pages contain plenty of information to help you get started. In particular, learn basic concepts regarding Typescript classes and template strings. As you will see in subsequent chapters, Angular applications rely heavily on dynamic templates, which frequently involve the interpolation (via the “{{}}” syntax) of variables. In addition, the following website provides an online “playground,” along with links for documentation and code samples about TypeScript:
https://www.typescriptlang.org/play/.
Angular takes advantage of ES6 features such as components and classes, as well as features that are part of TypeScript, such as annotations and its type system. TypeScript is preferred over ES6 because TypeScript supports all the features of ES6 and TypeScript provides an optional type inferencing system that can catch many coding errors.
Learn RxJS and Observables
If you have worked with ES6, then you probably know about functions such as the filter() function (which is handy for Angular Pipes) and the map() function (often used with Observables and HTTP requests in earlier versions of Angular). Other functions, such as merge() and flatten(), can also be useful, and you can learn about them and other functions on an as-needed basis.
In RxJS, the preceding functions are called “intermediate operators,” and you will frequently encounter them in RxJS Observables. In highly simplified terms, you can define an Observable involving one or more intermediate operators, and then invoke the Observable via a so-called “terminal operator.”
Different languages can support different methods as terminal operators, and in the case of RxJS, the subscribe() method is a terminal operator. RxJS Observables are more powerful than Promises, and knowledge of the latter will simplify your transition to RxJS Observables. After you learn the basic features of RxJS, the following (albeit more advanced) article contains very good information regarding the RxJS unsubscribe() method:
https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f.
Promises versus Observables
In Chapter 2 and Chapter 3, you will see examples of Angular applications that involve Observables. Although you can find online code samples that use Promises, Angular with TypeScript favors Observables. This book does not provide tutorial-like information regarding Observables (or Promises), but you can learn about the advantages of Observables over Promises at
https://www.syncfusion.com/blogs/post/angular-promises-versus-observables.aspx.
There are many other online tutorials available regarding Observables, and if necessary, you can read them on an as-needed basis in parallel with the code samples in the next two chapters. Fortunately, the code samples involve only a few features of Observables, so you do not need to become highly proficient with Observables for this book.
You can develop Angular applications in Electron, Webstorm, and Visual Studio Code. Check their respective websites for pricing and feature support.
A High-Level View of Angular
Angular was designed as a platform that supports Angular applications in a browser, server-side rendering, and Angular applications on mobile devices. The first aspect – rendering Angular applications in browsers – is the focus of this book. The second aspect – Angular Universal (a.k.a., server-side rendering) – is not discussed in this book, but in essence, server-side rendering creates the “first view” of an Angular application on a server instead of a browser. Since browsers do not need to construct this view, they can render a view more quickly and create a faster perceived load time. The third aspect – Angular applications on mobile devices – is outside the scope of this book.
Angular has a component-based architecture, where components are organized in a tree-like structure (the same is true of Angular modules). Angular also supports powerful technologies that you will learn in order to become proficient in writing Angular applications. The simplest way to create an Angular application is to use the Angular CLI (discussed in detail later) that generates the required files for an Angular application. Some of the important features of Angular are listed here:
one-way data binding
“tree shaking”
change detection
style encapsulation
The first two features are briefly discussed below. You can consult the online tutorials regarding style encapsulation.
One-way Data Binding in Angular
Angular provides declarative one-way binding as the default behavior (but Angular 4 enables you to switch to two-way binding if you wish to do so). One-way binding acts as a unidirectional change propagation that provides an improvement in performance as well as a reduction in code complexity. Angular also supports stateful, reactive, and immutable models. The meaning of the previous statement will become clearer as you work with Angular applications.
Angular applications involve defining a top-level (“root”) module that references a Component that in turn specifies an HTML element (via a mandatory selector property) that is the “parent” element of the Component. The definition of the Component involves a so-called “decorator” that contains a selector property and also a template property (or a templateUrl property).
The template property contains a mixture of HTML and custom mark-up that you can place in a separate file and then reference that file via the templateUrl property. In addition, the Component is immediately followed by a TypeScript class definition that contains “backing code” that is associated with component-related variables that appear in the template property. These details will become much clearer after you have worked with some Angular applications.
NOTE ThetemplateUrlproperty and styleUrlsproperty refer to files, whereas the templateproperty and stylesproperty refer to inline code.
A High-Level View of Angular Applications
Angular applications consist of a combination of built-in components and custom components (the latter are written by you), each of which is typically defined in a separate TypeScript file (with a ts extension). Each component uses one or more import statements to include its dependencies.
There are various types of dependencies available in Angular, such as directives and pipes. A custom directive is essentially the contents of a TypeScript file that defines a component. Thus, a custom directive consists of import statements, a Component decorator, and an exported TypeScript class.
Angular provides built-in directives, such as *ngIf (for if logic) and *ngFor (used in for loops). These two directives are also called “structural directives” because they modify the content of an HTML page. Angular built-in pipes include the date and numeric values (currency, decimals, numbers, and percent), whereas custom pipes are defined by you.
In addition, TypeScript classes use a decorator (which is a built-in function) that provides metadata to a class, its members, or its method arguments. Decorators are easy to identify because they always have an @ prefix. Angular provides a number of built-in decorators, such as @Component and @NgModule.
This concludes the high-level introduction to Angular features. The next portion of this chapter introduces the Angular CLI, which is used throughout this book to create Angular applications.
The Angular CLI
The Angular CLI is the official Angular application generator from Google. The Angular CLI is a command line tool called ng that generates complete Angular applications, which includes test-related code and also launches npm install in order to install the required files in node_modules. The home page for the Angular CLI is cli.angular.io.
The Angular CLI generates a configuration file called package.json to manage the “core” dependencies and their version numbers. After generating an Angular application, navigate to the node_modules subdirectory, and you will see an assortment of Angular subdirectories that contain files that are required for Angular applications.
Installing the Angular CLI
You need to perform several steps in order to install the Angular CLI: uninstall older versions (if you have any installed) of the CLI, then install the latest version of the CLI, and then create a new Angular application.
Step 1: uninstall the previous CLI (if you installed an older version) with the following:
sudo npm uninstall -g angular-cli npm cache clean
Step 2: install the new CLI with this command (note the new package name):
[sudo] npm install -g @angular/cli
The preceding command installs the ng executable, whose location you can find via the following command:
which ng
If the preceding command displays a blank line, that means that the directory that contains the ng executable is not included in the PATH environment variable. In this case, type the following command in a command shell:
export PATH=/Users/owner/.npm-global/bin:$PATH
Note that preceding command is valid for Mac OS X, Linux, bash, ksh, zsh, and any other Unix shells that are derived from the Bourne shell. If you are using Windows or a BSD-like shell (such as csh), search online to find the correct syntax for the preceding command for your system.
Now display the versions of the various components of the CLI by invoking the following command in a command shell:
ng version
As this book goes to print, the output of the preceding command will be something similar to what is shown below (version numbers might be slightly different for you):
Angular CLI: 8.3.21 Node: 13.3.0 OS: darwin x64 Angular: ...
Package
Version
@angular-devkit/architect
0.803.21
@angular-devkit/core
8.3.21
@angular-devkit/schematics
8.3.21
@schematics/angular
8.3.21
@schematics/update
0.803.21
rxjs
6.4.0
Features of the Angular CLI (optional)
Although this section contains useful information, you don’t need these details to create an Angular application (which you will see in the next section). After you have created some basic Angular applications and you want to incorporate additional functionality, you can return to this section and read about the Angular CLI options.
In order to see the various options of the ng executable, type the following command from a command shell (make sure that your PATH environment variable include the location of the ng executable, as discussed in a previous section):
$ ng help
Available Commands:
add
— Adds support for an external library to your project.
analytics
— Configures the gathering of the Angular CLI usage metrics. See
v8.angular.io/cli/usage-analytics-gathering
.
build (b)
— Compiles an Angular app into an output directory named
dist/
at the given output path. Must be executed from within a workspace directory.
config
— Retrieves or sets Angular configuration values in the angular.json file for the workspace.
doc (d)
— Opens the official Angular documentation (angular.io) in a browser, and searches for a given keyword.
e2e (e)
— Builds and serves an Angular app, then runs end-to-end tests using Protractor.
generate (g)
— Generates and/or modifies files based on a schematic.
help
— Lists available commands and their short descriptions.
lint (l)
— Runs linting tools on Angular app code in a given project folder.
new (n)
— Creates a new workspace and an initial Angular app.
run
— Runs an Architect target with an optional custom builder configuration defined in your project.
serve (s)
— Builds and serves your app, rebuilding on file changes.
test (t)
— Runs unit tests in a project.
update
— Updates your application and its dependencies. See update.angular.io/.
version (v)
— Outputs the Angular CLI version.
xi18n
— Extracts i18n messages from the source code.
version (v)
— Outputs the Angular CLI version.
xi18n
— Extracts i18n messages from the source code.
The ng g option is equivalent to the ng generate option, which enables you to generate an Angular custom Component, an Angular Pipe (discussed in Chapter 3), and other options. The ng x18n option extracts i18n messages from the source code. The next section shows you an example of generating an Angular custom Component in an application, and the contents of the files that are automatically generated for you.
The default prefix is app for components (e.g., <app-root></app-root>), but you can specify a different prefix with this invocation:
ng new app-root-name –prefix abc
NOTE Angular applications created viangalways contain thesrc/appdirectory.
Information about upgrading the Angular CLI is here:
https://github.com/angular/angular-cli.
Documentation for the Angular CLI is here:
http://cli.angular.io.
Now that you have an understanding of some of the features of the ng utility, let’s create our first Angular application, which is the topic of the next section.
A “Hello World” Angular Application
As you will discover, it’s possible to create many basic Angular applications with a small amount of custom code. When you are ready to create medium-sized applications, you can take advantage of the component-based nature of Angular applications in order to incrementally add new components (and modules).
Now let’s create a new project called HelloWorld by navigating to a suitable directory on your machine and then invoking the following command:
ng new HelloWorld
The Angular CLI generates everything except for your custom code. Second, the Angular CLI enables you to generate new components, routers, and so forth, which are possible with starter applications. Third, the Angular CLI is based purely on TypeScript, and the generated application includes the JSON files tsconfig.json, tslint.json, typedoc.json, and typings.json.
Now launch the HelloWorld application as follows:
cd HelloWorld ng serve
Launch a new browser session, navigate to localhost:4200, and you will see the same display as the content of Figure 1.1.
FIGURE 1.1 A Hello World Angular Application
NOTE Full color figures are available in the companion files.
The Anatomy of an Angular Application
The ng command that you launched in the previous section created an Angular application that contains more than 35,000 files, most of which are in the node_modules subdirectory. Fortunately, you only need to be aware of a handful of files when you need to create your own Angular applications.
Here is the list of files and directories in the root directory of the HelloWorld Angular application:
tslint.json
README.md
angular.json
browserslist
e2e
karma.conf.js
node_modules
package-lock.json
package.json
src
tsconfig.app.json
tsconfig.json
tsconfig.spec.json
tslint.json
.gitignore
.editorconfig
The most relevant files are package.json and angular.json and the most important directory for creating custom code in the src directory (all of these are shown in bold in the preceding list). In general, you will not need to modify either of these files. As you will see later in this chapter, you need to perform an extra step from the command line when you need to work with D3-based graphics.
The Main Files in the src/app Subdirectory (Overview)
The src subdirectory contains a combination of subdirectories and files, as shown here:
app
assets
environments
favicon.ico
index.html
main.ts
polyfills.ts
styles.css
test.ts
Notice that the preceding list contains the TypeScript file main.ts, which will be discussed later in this chapter.
Next, the src/app subdirectory contains your custom code and the src/assets subdirectory contains other assets, such as JSON files. Later you will see an example of an Angular application that reads the content of authors.json that is located in the src/assets subdirectory.
The following list displays the contents of the src/app subdirectory:
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
Unless it’s noted differently, you can delete the contents of app.component.html for every code sample in this book. The file app.component.ts contains TypeScript code that is specific to your Angular application, and the file app.module.ts specifies any dependencies in your Angular application, which can include Angular modules as well as custom modules (you’ll see examples of such in Chapter 3).
The three TypeScript files main.ts, app.component.ts, and app.module.ts are the bootstrap file, the main module, and the main component class, respectively, for Angular applications.
Here is the condensed one-sentence explanation about the purpose of these three files: Angular uses main.ts as the initial “entry point” to bootstrap the Angular module AppModule (defined in app.module.ts), which in turn references the main component AppComponent (defined in app.component.ts), as well as any other custom components (and modules) that you have imported into AppModule.
The Contents of the Three Main Files
The preceding section briefly described the sequence in which files are processed in Angular applications. The code samples this book involve custom code in the TypeScript file app.component.ts and sometimes involve updating the contents of the file app.module.ts, but there is no need to modify the file main.ts. The following subsections display the contents of these three files, along with a brief description of their contents.
The main.ts Bootstrap File
Listing 1.1 displays the contents of main.ts in the src subdirectory (not the src/app subdirectory) that imports and bootstraps the top-level Angular module AppModule. Although you won’t need to modify this file in the code samples in this book, it’s worth briefly taking a one-time look at the contents of this file.
This file acts as an “entry point” from which a sequence of files is accessed and then launched. As you will soon see, Angular applications have a component-based architecture, which might seem more complex than alternate frameworks. However, as you become more familiar with this architecture, you will see that this architecture enables teams of developers to work in parallel on different parts of a complex application.
LISTING 1.1 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.error(err));
The first line of code in Listing 1.1 is an import statement that is needed for the conditional logic later in the code listing. The second import statement appears in many Angular code samples, and it’s necessary for launching Angular applications on desktops and laptops.
The third import statement involves the top-level module of Angular applications, which in turn contains all the custom components and services that are included in this Angular module. The fourth import statement contains environment-related information that is used in the next conditional logic snippet: if the current application is in production mode, the enableProdMode() function is executed.
The final line of code is the actual bootstrapping process that involves rendering the code in app.component.ts in a browser.
The app.component.ts File
Listing 1.2 displays the content of app.component.ts, which illustrates the typical properties of an Angular application.
LISTING 1.2 app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
Listing 1.2 starts with an import statement for the Angular @Component decorator in order to define the metadata for the class AppComponent. At a minimum, the metadata involves two properties: selector and either template or templateUrl. Except for the routing-related components, both of these properties are required in custom components. In this example, the selector property specifies the custom element app-root (which you can change) that is in the HTML Web page index.html.
The templateURL property specifies a file that contains HTML markup that will be inserted in the custom element app-root. An alternative is the template property, which contains the HTML markup that will be inserted in the custom element app-root. The final line of code in Listing 1.2 is an export