35,99 €
As part of the Pocket Primer series, this book introduces basic deep learning concepts and integrates them into Angular 10 applications. It offers a fast-paced introduction to deep learning features and popular classifiers. Covering Angular 10 functionality, deep learning concepts, and key classification algorithms, the book includes code samples and figures. Topics such as TensorFlow and Keras are also explored.
The book begins with an introduction to AI and its applications, followed by state space search and heuristic search strategies. You will delve into expert systems, their development life cycle, knowledge acquisition, and representation. These topics lead to a deeper understanding of neural networks, the learning process, and fuzzy logic systems, ensuring a comprehensive grasp of AI and deep learning principles.
Understanding these concepts is essential for developing sophisticated AI applications and enhancing Angular 10 projects. This book transitions you from a novice to a proficient developer, equipped with practical skills and knowledge. Advanced topics like fuzzy expert systems and logic programming are covered, culminating in advanced Prolog. Companion files with source code and color figures enhance the learning experience, making this book an invaluable resource for integrating deep learning with Angular 10.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 381
Veröffentlichungsjahr: 2024
Copyright ©2021 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 20166
info@merclearning.com
www.merclearning.com
(800) 232-0223
O. Campesato. Angular and Deep Learning Pocket Primer.
ISBN: 978-1-68392-473-9
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: 2020946795
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 info@merclearning.com.
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 DEEP LEARNING INTRODUCTION
Keras and the XOR Function
What is Deep Learning?
What are Perceptrons?
The Anatomy of an Artificial Neural Network (ANN)
What is a Multilayer Perceptron (MLP)?
How are Datapoints Correctly Classified?
A High-Level View of CNNs
Displaying an Image in the MNIST Dataset
Keras and the Mnist Dataset
Keras, CNNs, and the Mnist Dataset
CNNS with Audio Signals
Summary
5 DEEP LEARNING: RNNs AND LSTMs
What is an RNN?
Working with RNNs and Keras
Working with Keras, RNNs, and MNIST
Working with TensorFlow and RNNs (Optional)
What is an LSTM?
Working with TensorFlow and LSTMs (Optional)
What are GRUs?
What are Autoencoders?
What are GANs?
Creating a GAN
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
The MNIST Dataset
Displaying MNIST Images
Training a Model with the CIFAR10 Dataset (optional)
Deep Learning and the MNIST Dataset
Angular, Deep Learning, and the MNIST Dataset
Summary
APPENDICES
A. INTRODUCTION TO KERAS
B. INTRODUCTION TO TF 2
C. TF 2 DATASETS
INDEX
PREFACE
What is The Goal?
The goal of this book is to introduce Web developers to deep learning and incorporate that knowledge in Angular 10 applications. This book is intended to be a fast-paced introduction to some basic features of deep learning and an overview of several popular deep learning classifiers and code samples.
This book will also save you the time required to search for code samples, which is a potentially time-consuming process. In any case, if you’re not sure whether or not 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 deep learning or Angular 10 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 concepts that you will encounter in deep learning, such as perceptrons, hyperparameters, activation functions, loss functions, and optimizers. Then you will learn about MLPs (Multi Layer Perceptrons) and CNNs (Convolutional Neural Networks). The fifth chapter discusses RNNs (Recurrent Neural Networks), LSTMs (Long Short-Term Memory), GRUs (Gated Recurrent Units), autoencoders, and GANs (Generative Adversarial Networks.
The sixth chapter introduces some preliminary TensorFlow concepts and a short introduction to TensorFlow.js (i.e., TensorFlow in modern browsers), followed by an example of Angular with TensorFlow.js and machine learning. The final portion of this chapter contains an example of Angular with TensorFlow.js and deep learning that involves the MNIST dataset. The appendices contain an introduction to Keras and TensorFlow 2, along with some basic code samples.
Another point: although Jupyter is popular, all the code samples in this book are Python scripts. However, you can quickly learn about the useful features Jupyter through various online tutorials. In addition, it’s worth looking at Google Colaboratory that is entirely online and is based on Jupyter notebooks, along with 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. The Keras-related code samples involve the XOR function, the MNIST dataset, CNNs, and RNNs. In most cases the code samples involve some understanding of activation functions, optimizers, and loss functions, all of which are discussed in Chapter 5.
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 “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 Deep 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 Deep 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. Regarding their content: the code samples are 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
Since the complete code samples requires more than 10GB 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 (note the version numbers for Angular and Node):
Angular CLI: 10.1.0-next.5
Node: 12.0.0
OS: darwin x64
Angular:
...
Ivy Workspace:
Package
Version
----------------------------------------------------
@angular-devkit/architect
0.1001.0-next.5
@angular-devkit/core
10.1.0-next.5
@angular-devkit/schematics
10.1.0-next.5
@schematics/angular
10.1.0-next.5
@schematics/update
0.1001.0-next.5
rxjs
6.6.2
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, which is shown in bold to make sure that you notice this comment:
// 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 got 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 and there’s a good chance that someone else has encountered the same error, along with a solution for that error.
What are the Technical Prerequisites for This Book?
For the deep learning portion of this book, some familiarity with basic Python is helpful, and also an understanding of how to launch Python code from the command line (in a Unix-like environment for Mac users). In addition, a general familiarity with basic linear algebra (vectors and matrices), probability/statistics (mean, median, standard deviation) and rudimentary concepts in calculus (such as derivatives) will sometimes be helpful for the material in this book.
Regarding 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 especially useful.
One other prerequisite is important for understanding the code samples in the second half of this book: some familiarity with neural networks, which includes the concept of hidden layers and activation functions (even if you don’t fully understand them).
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 deep 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 them the first time you encounter them, so be prepared to read the code samples several times.
Since you are probably a developer, you also know how to get additional help using online resources, such as documentation when you don’t understand a specific detail, or stackoverflow when you encounter an error in your code.
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 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 info@merclearning.com.
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 deep learning, there are many resources available, and you can perform an Internet search for those resources. The aspects of deep learning for you to learn depend on who you are: the needs of a deep learning engineer, data scientist, manager, student, or software developer are all different.
O. Campesato October 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, please keep in mind that you need to invest additional time and effort to acquire a deeper understanding of Angular. Although some of fine-grained details are discussed, you need to consult the online documentation to gain a thorough understanding of the features of Angular.
The purpose of the code samples in this book is to illustrate some fundamental features of Angular, and later you will learn about deep learning concepts that will enable you to incorporate deep learning in Angular applications.
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 the design goals of Angular and 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 10, using the ng command line utility for creating Angular applications.
There are several points to keep in mind before you read this book. First, the code samples highlight basic coding techniques in Angular applications. Hence, you will not find highly detailed descriptions of Angular concepts, design goals, and architecture that are available in 600-page books. However, you can fill in some of those gaps via online articles.
You can learn Angular concepts in the various applications without having previous experience with Angular, but some knowledge of Angular would be helpful.
This chapter contains 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 with no loss of continuity (and you can always return to them later).
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 are already familiar with Java, you will probably be more comfortable with TypeScript than JavaScript.
RxJS is JavaScript-based FRP (Functional Reactive Programming) that supports many intermediate operators, such as filter(), map(), take(), and many other useful operators. The following subsections contain some additional detail 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 node v6.14.7 and npm 12.0.0, but it’s likely that slightly lower versions will work as well. Determine the version on your machine with the following commands in a terminal:
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, you can find many online tutorials that explain how to use basic npm commands.
The code samples also involve basic concepts about ES6 and TypeScript, and their respective home pages contain plenty of information to help you get started. In particular, learn about classes and template strings. As you will see in subsequent chapters, Angular applications rely heavily on dynamic templates, which frequently involve 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 errors for you.
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 also 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, these 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 (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
Chapters 2 and 3 have examples of Angular applications that involve Observables. Although you can find online code samples that use Promises, Angular with TypeScript favors Observables. While this book does not provide tutorial-like information regarding Observables (or Promises), you can learn about the advantages of Observables over Promises here:
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 and provides support for server-side rendering and Angular applications on mobile devices. Rendering Angular applications in browsers is the focus of the chapters in this book. Angular Universal (aka 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. Angular applications on mobile devices are also outside the scope of this book.
Angular supports the most recent versions of Chrome and Firefox, as well as the two most recent versions of Edge, iOS, and Safari. The full list of supported browsers by the Angular framework is here:
https://angular.io/guide/browser-support
A Short List of Features
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. 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 and you should consult the online documentation regarding style encapsulation.
One-way Data Binding in Angular
Angular provides declarative one-way binding as the default behavior (but you can 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 The templateUrl property and styleUrls property refer to files whereas the template property and styles property refer to inline code.
New Features in Angular 10
Angular 10 introduces new features and also deprecates some earlier features. It provides improved performance and a reduced application size. Some of the main differentiating features in Angular 10 are listed here:
New Date Range Picker
The Ivy Renderer
Language Service
Localization
TypeScript 3.9
The --strict Option
In brief, the new date range picker is available in Angular Material, along with some relatively minor changes to other features. The Ivy renderer provides the improvements in terms of increased performance and reduced application size.
Angular 10 was released in June 2020 and supports TypeScript 3.9. Since TypeScript 4.0 was released in August 2020, perhaps this version (or an even new version) will be supported in Angular 11. In case you’re interested, you can learn about TypeScript 4.0 here:
https://devblogs.microsoft.com/typescript/announcing-typescript-4-0/
One other important change in Angular 10 is its support for the --strict option for the ng command line utility that performs stricter type checking in your custom code. For instance, the following snippet compiles successfully without the --strict option:
However, if you create an Angular application with the --strict option, then the following code snippet is required because the previous snippet is invalid:
employees : any;
These (and other) differences are noted in the Angular 10 applications in this chapter that were created with the --strict option. Keep in mind that the Angular 10 applications in all other chapters were created without the --strict option.
The node and npm Utilities for Angular 10
If you do not have the node utility (which also contains the npm utility) on your machine, download the distribution from this link:
https://www.npmjs.com/get-npm
Important: Angular 10 requires a version of the node executable whose version number is in the following range (which is specified in package.json):
"node": ">=10.9.0 <13.0.0"
All the Angular applications in this book were created with the following version of the npm and node utilities (the version of ng is displayed later in this chapter):
$ npm --version
6.14.7
$ node --version
v12.0.0
After this book goes to print, it’s possible that higher versions of node and npm will be compatible with Angular 10 applications: the range of version numbers for node are available in the file package.json.
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 (for loops). These two directives are also called “structural directives” because they modify the content of an HTML page. Angular built-in pipes include date and numeric (currency, decimal, number, and percent) formats, 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 ng utility is an Angular command-line utility for creating (via ng new) Angular applications and for launching (via ng serve) Angular applications. The Angular CLI is the official Angular application generator from Google. The ng utility generates complete Angular applications, which includes test-related code, and (by default) launches npm installto install the required files in node_modules. A concise set of examples for the Angular CLI is here:
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
If you do not have the ng utility already installed on your machine, you can download the latest version of Angular here:
https://github.com/angular/angular/releases
If you already have the ng utility installed on your machine, you can perform an upgrade to Angular 10 from an earlier release of Angular as follows:
ng update @angular/cli @angular/core
The ng utility has many useful options, and you can find detailed information regarding the ng utility here:
https://angular.io/cli
If you encounter issues during the creation of Angular 10 applications, you might also need to uninstall an older version of the CLI and install the latest version of the CLI. You can uninstall an older version with this command:
sudo npm uninstall -g angular-cli
npm cache clean
Next, 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, 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 is something similar to what is shown below (version numbers might be slightly different for you):
Angular CLI: 10.1.0-next.5
Node: 12.0.0
OS: darwin x64
Angular:
...
Ivy Workspace:
Package
Version
------------------------------------------------------
@angular-devkit/architect
0.1001.0-next.5
@angular-devkit/core
10.1.0-next.5
@angular-devkit/schematics
10.1.0-next.5
@schematics/angular
10.1.0-next.5
@schematics/update
0.1001.0-next.5
rxjs
6.6.2
Features of the Angular CLI (optional)
Although this section contains useful information, you don’t need these details in order to create an Angular application (which you already did in the previous 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 has been set correctly, 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 Angular CLI usage metrics. See
https://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.
deploy:
Invokes the deploy builder for a specified project or for the default project in the workspace
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
Sio/version(v):
Outputs Angular CLI version
xi18n (i18n-extract):
Extracts i18n messages from source code
For more detailed help,type ng [command name] –help.
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 5), and so forth. The ng x18n option extracts i18n messages from 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 via ng always contain the src/app directory.
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
In addition, Angular 10 supports the --strict option when creating Angular applications, an example of which is here:
ng new --strict HelloWorld
The preceding command results in stricter type checking in Angular 10 applications, which you will see later in this chapter. If you encounter difficulties when you specify the preceding command-line option, you can revert to the older style of creating Angular applications.
NOTE Only the first three Angular 10 applications in this chapter specify the --strict switch when creating them via the ng utility.
The Angular CLI provides 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.
You will see the following type of output in the command shell where you launched the preceding command:
? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? CSS
CREATE HelloWorld/README.md (1035 bytes)
CREATE HelloWorld/.editorconfig (274 bytes)
CREATE HelloWorld/.gitignore (631 bytes)
CREATE HelloWorld/angular.json (3686 bytes)
CREATE HelloWorld/package.json (1331 bytes)
CREATE HelloWorld/tsconfig.json (697 bytes)
CREATE HelloWorld/tslint.json (3205 bytes)
CREATE HelloWorld/.browserslistrc (853 bytes)
CREATE HelloWorld/karma.conf.js (1022 bytes)
CREATE HelloWorld/tsconfig.app.json (287 bytes)
CREATE HelloWorld/tsconfig.spec.json (333 bytes)
CREATE HelloWorld/src/favicon.ico (948 bytes)
CREATE HelloWorld/src/index.html (296 bytes)
CREATE HelloWorld/src/main.ts (372 bytes)
CREATE HelloWorld/src/polyfills.ts (2835 bytes)
CREATE HelloWorld/src/styles.css (80 bytes)
CREATE HelloWorld/src/test.ts (753 bytes)
CREATE HelloWorld/src/assets/.gitkeep (0 bytes)
CREATE HelloWorld/src/environments/environment.prod.ts (51 bytes)
CREATE HelloWorld/src/environments/environment.ts (662 bytes)
CREATE HelloWorld/src/app/app.module.ts (314 bytes)
CREATE HelloWorld/src/app/app.component.css (0 bytes)
CREATE HelloWorld/src/app/app.component.html (25725 bytes)
CREATE HelloWorld/src/app/app.component.spec.ts (952 bytes)
CREATE HelloWorld/src/app/app.component.ts (214 bytes)
CREATE HelloWorld/src/app/package.json (817 bytes)
CREATE HelloWorld/e2e/protractor.conf.js (869 bytes)
CREATE HelloWorld/e2e/tsconfig.json (294 bytes)
CREATE HelloWorld/e2e/src/app.e2e-spec.ts (643 bytes)
CREATE HelloWorld/e2e/src/app.po.ts (301 bytes)
Installing packaI...
Packages installed successfully.
Successfully initialized git.
Now launch the HelloWorld application by navigating into the src subdirectory of the HelloWorld application and then launching the ng command, as shown here:
cd HelloWorld/src
ng serve
Compiling @angular/core : es2015 as esm2015
Compiling @angular/common : es2015 as esm2015
Compiling @angular/platform-browser : es2015 as esm2015
Compiling @angular/platform-browser-dynamic : es2015 as esm2015
chunk {main} main.js, main.js.map (main) 57.1 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.5 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 2.37 MB [initial] [rendered]
Date: 2020-08-13T23:10:47–037Z - Hash: acec74a5d422175–701e - Time: 21053ms
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
: Compiled successfully.
Date: 2020-08-13T23:10:48–965Z - Hash: acec74a5d422175c701e
5 unchanged chunks
Time: 1425ms
: Compiled successfully.
Launch a new browser session, navigate to localhost:4200, and you will see the same contents as shown in Figure 1.1.
FIGURE 1.1 A “Hello World” Angular application
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 focus on 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:
node_modules
package-lock.json
README.md
angular.json
e2e
karma.conf.js
package.json
src
tsconfig.app.json
tsconfig.json
tsconfig.spec.json
tslint.json
The most relevant files are package.json and angular.json, and the most important directory for creating custom code is the src directory (all of these are shown in bold in the preceding list). In general, you do 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 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, which 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
package.json
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 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 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 sections display the contents of these three files and include a brief description of their contents.
The main.ts Bootstrap File
Listing 1.1 shows the content of main.ts in the src subdirectory (not the src/app subdirectory) that imports and bootstraps the top-level Angular module AppModule. Angular applications have a component-based architecture, which might seem more complex than alternate frameworks. However, 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 shows 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 metadata for the class AppComponent. At a minimum, the metadata involves two properties: selector and either template or templateUrl. Except for 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 is inserted in the custom element app-root. An alternative is the template property that contains the HTML markup that is inserted in the custom element app-root. The final line of code in Listing 1.2 is an export statement that makes the AppComponent class available for import in other TypeScript files, such as app.module.ts, which is shown in Listing 1.3 in the next section.
Although the property templateUrl specifies an HTML Web page with mark-up, the Angular code samples in this book use the template property to define the layout of the HTML web page for Angular applications (that’s why the HTML Web page app.component.html in the code samples in this book is empty).
The app.module.ts File
Listing 1.3 shows the content of app.module.ts, which displays the dependencies of various modules in an Angular application.
LISTING 1.3: app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Listing 1.3 contains import statements that import BrowserModule and NgModule. The third import statement imports the class AppComponentthat is the top-level component illustrated in Listing 1.2 in the previous section.
NOTE Angular dependencies always contain the “@” symbol whereas custom dependencies specify a relative path to TypeScript files.
Next, the @NgModule decorator contains an object with various properties (discussed in the next section). These properties specify the metadata for the class AppModule that is exported in the final line of code in Listing 1.3. The metadata in AppModule involves the following array-based properties of values: imports, providers, declarations, exports, and bootstrap.
In Listing 1.3, the array properties declarations, imports, and bootstrap are non-null, whereas the providers property is an empty array. This metadata is required in order for Angular to “bootstrap” the code in AppComponent, which in turn contains the details of what is rendered (e.g., an <h1> element) and where it is rendered (e.g., the app-root element in index.html).
Now let’s take a look at the contents of the HTML Web page index.html, which contains the main Web page for our Angular application.
The index.html Web Page
Listing 1.4 shows the contents of index.html for a new Angular application that is generated from the command line via the ng utility.
LISTING 1.4: index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HelloWorld</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>
Listing 1.4 is minimalistic: only the custom <app-root> element (which is specified in the selector property in app.component.ts) gives you an indication that this Web page is part of an Angular application.
NOTE The Angular CLI automatically inserts JavaScript dependencies in index.html during the “build” of the project.
Before we delve into the TypeScript files in an Angular application, let’s take a quick detour to understand how import statements work in Angular applications. Feel free to skip the next section if you are already familiar with import and export statements in Angular.
Exporting and Importing Packages and Classes (optional)
Every TypeScript class that is imported in a TypeScript file must be exported in the TypeScript file where that class is defined. You will see many examples of import and export statements: in fact, this is true of every Angular application in this book.
There are two common types of import statements: one type involves importing packages from Angular modules, and the other type involves importing custom classes (written by you). Here is the syntax for both types:
import {some-package-name} from 'some-angular-module';
import {some-class } from 'my-custom-class';
Here is an example of both types of import statements:
import { NgModule } from '@angular/core';
import {EmpComponent} from './emp.component';
In the preceding code snippet, the NgModule package is imported from the @angular/core module that is located in the node_modules directory. The EmpComponent class is a custom class that is defined and exported in the TypeScript file emp.component.ts.
In the second import statement, the “./” prefix is required whenever a custom class is imported from a TypeScript file: notice the omission of the “.ts” suffix.
Working with Components in Angular
As you have already learned, an Angular application is a tree of nested components, where the top-level component is the application. The components define the UI elements, screens, and routes. In general, organize Angular applications by placing each custom component in a TypeScript file and then import that same TypeScript file in the “main” file (which is often named app.component.ts) that contains the top-level component.
The MetaData in Components
Angular components are often a combination of an @Component decorator and a class definition that can optionally contain a constructor. A simple example of an @Component decorator is here:
import { Component } from '@angular/core';
import {EmpComponent} from './emp/emp.component';
@Component({
selector: 'app-container',
template: '<tasks>{{message}}</tasks>',
directives: [EmpComponent]
})
The preceding @Component decorator contains several properties, some of which are mandatory and others that are optional. Let’s look at both types in the preceding code block.
The selector property is mandatory, and it specifies the HTML element (whether it’s an existing element or a custom element) that serves as the “root” of an Angular application.
Next, the template property (or a templateUrl property) is mandatory, and it contains a mixture of markup, interpolated variables, and TypeScript code. One important detail: the template property requires “backticks” when its definition spans multiple lines. The directives property is an optional property that specifies an array of components that are treated as nested components. In this example, the directives property specifies the component EmpComponent, which is also imported (via an import statement) near the beginning of the code block. Notice that the import statement does not contain a “@” symbol, which means that EmpComponent is a custom component defined in the file emp/emp.component.ts.
Stateful versus Stateless Components in Angular
Tausende von E-Books und Hörbücher
Ihre Zahl wächst ständig und Sie haben eine Fixpreisgarantie.
Sie haben über uns geschrieben: