Appendix B

Angular Cheat Sheet

Here is a quick reference cheat sheet for you to familiarize yourself with common Angular syntax and CLI commands. Take some time to review and orient yourself with new Angular syntax, major components, CLI scaffolds, and common pipes.

You may find the list especially useful if your background is with AngularJS, since you will need to unlearn some old syntax.

If you are new to Angular or simply not a fan of CLI commands, check out Nx Console at https://nx.dev/angular/cli/console, an awesome desktop app, and a Visual Studio Code extension, that can write your CLI arguments for you. That said, I do recommend that you first gain familiarity with the CLI commands and force yourself to use them for a bit, so you have a better understanding of how Nx Console works.

Binding, or data binding, refers to an automatic one or two-way connection between a variable in code and a value displayed or inputted in an HTML template or another component:

Type Syntax Data direction

Interpolation Property Attribute Class

Style

{{expression}} [target]="expression" bind-target="expression"

One-way,

from data source to view target

Event

(target)="statement" on-target="statement"

One-way,

from view target to data source

Two-way

[(target)]="expression" bindon-target="expression"

Two-way

Built-in directives

Directives encapsulate coded behaviors that can be applied as attributes to HTML elements or other components:

Name Syntax Purpose

Structural Directives

*ngIf

*ngFor

*ngSwitch

Controls the structural layout of the HTML and if elements get added or removed from the DOM

Attribute Directives

[class] [style] [(model)]

Listens to and modifies the behavior of other HTML elements, attributes, properties, and components, such as CSS classes, HTML styles, and HTML form elements

Common pipes

Pipes (known as filters in AngularJS) modify how a data-bound value is displayed in an HTML template:

Name Purpose Usage

Async

Manages subscriptions to observables, and provides synchronous access to the variable in the template

someVariable$ | async as someVariable

Date

Formats a date according to locale rules

{{date_value | date[:format]}}

Text Transformation

Transforms text to uppercase, lowercase, or title case

{{value | uppercase}}

{{value | lowercase}}

{{value | titlecase }}

Decimal

Formats a number according to locale rules

{{number | number[:digitInfo]}}

Percent

Formats a number as a percentage according to locale rules

{{number | percent[:digitInfo]}}

Currency

Formats a number as currency with a currency code and symbol according to locale rules

{{number | currency [:currencyCode [:symbolDisplay [:digitInfo]]]}}

Starter commands, major components, and CLI scaffolds

Starter commands help generate new projects or add dependencies. Angular CLI commands help create major components by automatically generating boilerplate scaffolding code with ease. For the list of the full set of commands, visit https://github.com/angular/angular-cli/wiki.

Starter commands

Here are the most basic commands, which you will probably memorize over time and use the most often. Remember never to install @angular/cli globally as covered in Chapter 3, Creating a Basic Angular App:

Name Purpose CLI command

New

Creates a new Angular application with an initialized Git repository, package.json, with routing already configured and Ivy enabled. Run from the parent folder.

npx @angular/cli new project-name --routing

Update

Updates Angular, RxJS, and Angular Material dependencies. Rewrites code, if necessary, to maintain compatibility.

npx ng update

Add Material

Installs and configures Angular Material dependencies.

npx ng add @angular/material

Major component scaffolds

Use the following commands during your daily workflow to add new components, services, and other major components to your Angular application. These commands will save you serious time and help you avoid simple configuration mistakes:

Name Purpose CLI command

Module

Creates a new @NgModule class. Uses -- routing to add routing for submodules. Optionally, import the new module into a parent module using --module.

n g module my-module

ng g m my-module

Component

Creates a new @Component class. Uses -- module to specify the parent module. Optionally, use --flat to skip directory creation, -t for an inline template, and -s for an inline style.

ng g component my-component

ng g c my-component

Directive

Creates a new @Directive class. Optionally, uses --module to scope directives for a given submodule.

ng g directive my-directive

ng g d my-directive

Pipe

Creates a new @Pipe class. Optionally, use --module to scope pipes for a given submodule.

ng g pipe my-pipe

ng g p my-pipe

Service

Creates a new @Injectable class. Uses --module to provide a service for a given submodule. Services are not automatically imported to a module. Optionally use --flat false to create a service under a directory.

ng g service my-service

ng g s my-service

Guard

Creates a new @Injectable class, which implements the Route lifecycle hook CanActivate. Uses --module to provide a guard for a given submodule. Guards are not automatically imported to a module.

ng g guard my-guard

ng g g my-guard

In order to properly scaffold some of the components listed earlier under a custom module, such as my-module, you can prepend the module name before the name of what you intend to generate, for example, ng g c my-module/my-new-component. The Angular CLI will properly wire up and place the new component under the my-module folder.

TypeScript scaffolds

If you are not familiar with the TypeScript syntax, these TypeScript-specific scaffolds will help you create classes, interfaces, and enums, so you can leverage object-oriented programming principles to reduce the duplication of code and implement code behavior like calculated properties in classes rather than components:

Name Purpose CLI command

Class

Creates a barebones class

ng g class my-class

Interface

Creates a barebones interface

ng g interface my-interface

Enum

Creates a barebones enum

ng g enum my-enum

Common RxJS functions/operators

In order to become an effective Angular developer, you need to become an RxJS master. Here are some of the most common and useful RxJS operators for quick reference:

Functions

Name Purpose

pipe

Takes one or more observables as input and generates an observable as output, allowing you to build custom data streams.

subscribe

Required to activate an observable. It is an anti-pattern to extract the value of an observable data stream from a subscribe operation. An Async pipe or the tap function can be used to inspect or use the current value.

unsubscribe

Releases resources and cancels observable executions. Not unsubscribing can lead to performance problems and memory leaks. Use the Async pipe or the SubSink library to manage subscriptions.

Operators

Name Purpose

of

Converts the provided value to an observable sequence. Useful for integrating synchronous code into an observable data stream.

from

Creates an observable from an array, an iterable object, or a promise.

map

Allows you to iterate through every value that is emitted by the observable.

merge

Creates an output observable that concurrently emits all values from every given input observable. Useful for triggering an action based on multiple observables.

combineLatest

Combines values from multiple observables with the latest value from each observable. Useful when used in tandem with the merge operator.

filter

Filters values in the data stream. Useful to ignore null values or only execute the rest of the pipeline when some condition is met.

concat

Sequentially emits values from multiple observables. Useful for synchronizing multiple operations. Variants like concatMap can also flatten the observable, which is useful for iterating over values of collections.

take

Given a count, automatically completes the observable after consuming the prescribed number of times.

catchError

Catches errors on the observable to be handled by returning a new observable or throwing an error.

scan

Using an accumulator function, it can process data incrementally. That is, getting a running subtotal as numbers are added. Useful for long-running operations where you need an update.

Thanks to Jan-Niklas Wortmann for reviewing this section. Keep up with him on Twitter: @niklas_wortmann.

Further Reading