© Venkata Keerti Kotaru 2020
V. K. KotaruAngular for Material Designhttps://doi.org/10.1007/978-1-4842-5434-9_2

2. Getting Started

Venkata Keerti Kotaru1 
(1)
Hyderabad, India
 

This chapter is a “getting started” guide for Angular applications made with TypeScript and Material Design. By the end of the chapter, you should be able to set up a sample project—a basic “Hello World” version of an Angular application made with TypeScript and Material Design. This chapter introduces concepts that are elaborated in upcoming chapters.

This chapter begins by describing the prerequisites for starting a sample application. We run it to see the first page. The chapter also introduces basic scripts for running an application for development, and packaging, building, and generating static code analysis results.

This chapter introduces a sample application and a storyline used throughout the book. The goal is to achieve consistency in the application’s requirements, which helps you better understand Angular, TypeScript, and Material Design concepts.

Prerequisites

Before we start developing the Angular application with TypeScript and Material Design, the following prerequisites need to be set up on your development machine to work with this book’s examples and instructions.

Node.js

Node is a JavaScript runtime. Preferably, you should use the latest version of Node. At the time of writing this content, Angular recommends using Node version 8.x or 10.x.

To verify that you have Node installed on your machine, run the following command in the terminal (Mac) or command prompt (Windows).
node -v

If Node is correctly installed on your machine, the command returns a version number. If it is not installed, this command shows an error. Download and install Node from https://nodejs.org.

Package Managers

While working with the Angular application, you will need a package manager. A JavaScript application or a library has dependencies. These dependencies have more dependencies. A package manager makes it easy to install and manage these dependencies.

npm and Yarn are two popular JavaScript package managers; both are open source. This book provides instructions for both options.

npm

npm is installed along with Node.js. It is the most popular JavaScript package manager. Millions of developers use it and download packages from its repository every day.

Yarn

While npm is reliable and has a huge developer user base, there is scope for improvement. Yarn is relatively fast. It made improvements to its security when running a package’s dependencies. It is an open source project driven by Facebook, Google, Exponent, and Tilde.

To install Yarn, run the following command.
npm install --global yarn

Note

This command installs Yarn globally on the machine. You will need administrative privileges (run the command prompt as an admin) on a Windows machine, or you need super user access on a Mac (sudo npm install --global yarn).

If you are new to either of these package managers, pick one and consistently use it while performing the examples in this book.

Angular CLI

Angular CLI is a powerful tool for improving developer productivity. It helps create a new Angular project from scratch and maintains the project throughout the development life cycle.

Throughout the book, we primarily use Angular CLI for various development tasks (on the sample project); however, where necessary, I provide alternatives that don’t use Angular CLI.

Angular CLI helps improve productivity a great deal, but by no means is it a mandatory tool.

Install Angular CLI

It is preferable to install Angular CLI globally on the machine.

Run the following command for npm.
npm install --global @angular/cli
Run the following command for Yarn.
yarn global add @angular/cli

Note

Angular CLI is installed globally on the machine. Use sudo on Macs and administrator privileges on Windows.

Visual Studio Code

You need an editor or an IDE to work with Angular and TypeScript code. Choosing a particular editor is a personal choice. I’ve seen many developers who are very good with a vi editor. They prefer doing everything with a keyboard, without switching to a mouse, for the speed. There are other choices, like Sublime, Atom, or even a simple text editor like Notepad in Windows.

My recommendation is Visual Studio Code. First, it is free, lightweight, and open source. The features set is driven by Microsoft. I’ve always seen monthly updates that add features and enhancements.

Visual Studio Code is great for working with TypeScript. It quickly shows warnings and errors as you type code. There are easy-to-peek-into definitions for the functions. It also has a good echo system and extensions created by developers from around the world. To install Visual Studio Code, download it from https://code.visualstudio.com.

Having said that, however, pick an editor that you are comfortable with.

Getting Started with a Sample Application

To start an Angular application using TypeScript and Material Design, consider the following two options.
  • Use Angular CLI, which creates a new Angular application with TypeScript and Material Design. Angular CLI is a productivity tool that is helpful with creating and maintaining the sample application. Throughout the book, we add many features to the sample application using Angular CLI.

  • Manually add Material Design to an existing Angular and TypeScript application.

Option 1: Getting Started Using Angular CLI

To use Angular CLI to start an Angular project, run the following command.
ng new superheroes --routing

superheroes is the name of the sample project. This project creates and lists superheroes and their data.

The routing option (--routing) includes a routing module and default configuration values. Routing is important when building a single-page application. We explore this more in upcoming chapters.

After installation, use the following command to install the Angular Material CLI schematic. It helps install the required dependencies for Material Design.
ng add @angular/material
Figure 2-1 shows the details of the command, which prompts the following.
  • A Material Design theme selection.

  • Optional setup of Hammer JS for gesture support. This is useful on touch screen devices like iPhones or Android phones, tablets, and multitouch-supported laptop or desktop screens. For the current project, select Yes.

  • Optional setup of browser animations. Choose Yes for the sample project.

  • Choose your style sheet options. For simplicity, select CSS.

../images/475625_1_En_2_Chapter/475625_1_En_2_Fig1_HTML.jpg
Figure 2-1

Add Angular Material schematic

The application is generated, installed, and ready to use. Use the following command to see the application compiled and up and running. We can further develop and debug the application with a start script running in the background. Figure 2-2 shows the start script configuration. Figure 2-3 shows a first look at the up-and-running application.
../images/475625_1_En_2_Chapter/475625_1_En_2_Fig2_HTML.jpg
Figure 2-2

Run the start script to see the application working

../images/475625_1_En_2_Chapter/475625_1_En_2_Fig3_HTML.jpg
Figure 2-3

First look at the generated application

Use the following with Yarn.
yarn start
Use the following with npm.
npm start

Please note that in the sample, Material Design is installed but has not been used yet. It is a starter project with Angular and TypeScript. The next few sections add Material Design references in the code.

Note

Jump to the “Add Material Design Code References” section to continue with the newly created Angular application with CLI. Option 2 describes the changes required for an existing Angular application to include Material Design.

Option 2: Material Design for an Existing Application Without Angular CLI

If you have an existing Angular project that doesn’t use Angular CLI, consider the following instructions.

Install Angular Material Packages

For npm, use the following command to install Material Design and related packages.
npm install --save @angular/material @angular/cdk @angular/animations
For Yarn, use the following command to install Material Design and related packages.
yarn add @angular/material @angular/cdk @angular/animations

Reference Style Sheet/Theme

To use an existing theme provided by Angular Material, use the following line of code you styles.css (or an equivalent global style sheet file). Notice we are using the Indigo Pink theme.
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Reference Font and Material Design Icons

Update index.html (or an HTML file loading the Angular content). Add the following references, which bring Material Design typography, fonts, and icons to the application, respectively.
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Follow the next few sections to add code references for Material Design, and run the project as you always do (considering that it is an existing project). Typically, npm start is used to start an Angular project (or any JavaScript project) for development and debugging purposes.

Add Material Design Code References

The required packages (Material, CDK, and Animations) for Material Design have already been installed. Now, let’s add the code references. For the first example, let’s add a Material Design toolbar and a card to the application.

Module Reference

The toolbar and card are packaged in their own Angular module. Refer to Listing 2-1 to import the modules to the TypeScript file and the NgModule. Open src/app.module.ts and make the changes mentioned in Listing 2-1.

An Angular module is different from a JavaScript module. It encapsulates Angular components, services, and so forth. A component in a module is scoped internally. It can only be used across modules when exported from the containing module.

I explain Angular modules in an upcoming chapter.
--- app.module.ts ----
// 1. Add the following line
// Import toolbar and card modules
import { MatToolbarModule, MatCardModule } from '@angular/material';
/∗ Considering it is a getting started sample, importing noop animation module, disabling animations. ∗/
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
// 2. Update imports with the two additional modules
@NgModule({
// Deleted additional properties for brevity
 imports: [
   MatToolbarModule,
   MatCardModule,
   NoopAnimationsModule
 ],
})
export class AppModule { }
Listing 2-1

Module References

Modify Template

Update the app component template to show the Material Design toolbar and card. Delete the code in src/app/app.component.html and replace it with the code in Listing 2-2.

An Angular component has a template, which is HTML code that takes care of the presentation logic. It acts as the view for the component.
<mat-toolbar color="primary">Superheroes</mat-toolbar>
<mat-card> Hello Material Design World</mat-card>
<router-outlet></router-outlet>
Listing 2-2

Template Using Toolbar and Card

As you save the two files, the application recompiles and refreshes the browser to show the result (see Figure 2-4).
../images/475625_1_En_2_Chapter/475625_1_En_2_Fig4_HTML.jpg
Figure 2-4

Material Design

Sample Application

As you embark on the journey of learning how to create Angular applications with TypeScript and Material Design, it is easier to visualize the concepts with an example. It is a sample application that we will build as you learn the concepts in the book. It helps to have a consistent story.

Storyline

We will build an application for superheroes. You might have noticed the name of the sample application generated with Angular CLI.

The application allows the superheroes’ data to be added, modified, and deleted. A superhero can search for and list other superheroes, view the details, and maybe fight other superheroes. Fights might be in movies but not in our app!

Features

In the upcoming chapters, we continue to build the superheroes application. The following are the high-level requirements for the application
  • Superheroes like sophistication in functionality. The application needs multiple screens. It needs to be built as an SPA (single-page application) so that there are no page reloads when transitioning between pages.

  • Superheroes like consistency. The application needs a consistent look and feel. The controls on the pages— labels, buttons, drop-downs, lists of items—need to look and behave the same way across the application.

  • Superheroes like to make life easier. The application needs to be intuitive; for example, the user should be able to locate the primary actions at a consistent location on the pages. The user needs to easily find the functionalities.

The following are the set of screens and low-level functionalities to build with the Angular application using TypeScript and Material Design.
  • An intuitive list of superheroes with images and interactive animations

  • The ability to filter

  • A detailed information screen for each superhero

  • A form to create a new superhero

  • The ability to edit a superhero

Note

At this point, you have everything to move to the next chapter. We have a basic development environment set up, and the sample application is up and running. The remaining sections describe the files and folders generated by CLI, which is nice-to-have information (at this stage).

Files and Directories Generated by CLI

Let’s review the files and directories generated with Angular CLI. This section provides a high-level overview of the files generated. At the end of this section, you will understand the purpose of each file. The sections do not detail all of the available options and configurations.

Configuration Files at the Root

At the root of the application, many configuration files have been generated. Consider the following file list. They are the primary configuration files. There could be additional configurations, depending on the IDE, the source control product, and so forth.

Package.json

Package.json is a primary configuration file for the new application package. It maintains the name of the application, the version number, and other types of metadata. npm (Node Package Manager) or Yarn maintain the application and dev dependencies here. It is the root file using the generated and installed dependency tree.

It also has configuration for scripts, which are the common tasks performed when developing, unit testing, and building the application. The scripts in a CLI-generated application depend on an Angular workspace configuration.

angular.json

angular.json is a workspace configuration file. Angular CLI creates this file when the first Angular project is generated. More projects can be added to the workspace, including libraries, end-to-end test projects, and so forth. Angular commands and configurations are in this file. Some of the configurations include the following.
  • Serve, a configuration for running the application for development purposes

  • Build, a configuration for compiling and bundling the Angular application.

  • Production optimization options

  • Unit test and end-to-end test configurations

tsconfig.json

tsconfig.json is a TypeScript configuration file. It has TypeScript compiler options, module system–related configurations, a directory location for type definitions, and so on.

It is the root configuration. For each project in the workspace, there is a specific TypeScript configuration, which extends the configuration from this file at the root directory. Remember, we are in the context of a workspace when we generate an application with Angular CLI; that is, we first have a default project created. More projects can be added to the workspace.

tslint.json

tslint.json is a lint configuration for TypeScript code. This book extensively uses TypeScript. The linting process ensures code quality, adherence to coding standards, and static code analysis. TSLint checks TypeScript and Angular application code against configured rules and warns about any discrepancies.

This is the root configuration. For each project in the workspace, there is a specific lint configuration that extends the configuration from this file at the root directory. Remember, we are in the context of a workspace when we generate an application with Angular CLI; that is, we first have a default project created. More projects can be added to the workspace.

Default Application Directory Root: /src

The first generated Angular application is placed in the /src directory at the root of the project. As mentioned, when you use CLI in a new directory, the first project is generated under the /src folder, and it is the default project in the workspace. As we generate more projects with CLI, they are moved under a /projects folder. The default project remains as the first generated project in /src. You can manually change it.

Consider the following files and directories in the /src folder..

TypeScript Configurations

/-
--/src
---/src/tsconfig.app.json
---/src/tslint.json
---/src/tsconfig.spec.json

tsconfig.app.json and tsconfig.spec.json extend from /tsconfig.json, which is the workspace-level TypeScript configuration file. The tsconfig.app.json file provides the TypeScript configuration for the application files. tsconfig.spec.json provides the TypeScript configuration for the unit test files, which are post-fixed with .spec.ts.

The tslint.json file in /src extends from tslint.json at the root directory. It provides a specific linting configuration for the default project.

If we create more projects using CLI, each project will have its own tsconfig and tslint configuration files.

index.html

index.html is the primary HTML file. It references the application files and dependencies, style sheets, and so on. This file references the root component for the Angular application. Consider the following code for a body tag, which loads the root component of a generated Angular application called app-root.
<body>
 <app-root></app-root>
</body>

main.ts

The main.ts file has the code to bootstrap the Angular application. Consider Listing 2-3.
platformBrowserDynamic()
  .bootstrapModule(AppModule)
 .catch(err => console.error(err));
Listing 2-3

Bootstrap the Angular Application

The file also has code to conditionally enable the production mode (see Listing 2-4). The framework performs assertions in the development mode; for example, an assertion to ensure that a change detection pass does not result in additional unexpected changes. If it notices changes between two change detection patterns, it throws a warning that indicates a possible bug. When production mode is enabled, such assertions are removed.
if (environment.production) {
 enableProdMode();
}
Listing 2-4

Enable Production Code Based on a Condition

Application Directory: /src/app

Application code—including modules, components, and services—are placed in this directory. I explain each concept in upcoming chapters; however, the following introduces the purpose of each file.

Root Module: app.module.ts

src/app/app.module.ts is the root Angular module for the default project generated with Angular CLI. In Listing 2-5, the Angular module is created by decorating a TypeScript class with NgModule.

Note that the Angular module is different from a JavaScript module. Angular modules may contain one or more components, services, and other Angular code files. It scopes these units of code; that is, if a component in module-1 needs to be used in module-2, it needs to be exported explicitly.
@NgModule({
 // Removing decorator properties for brevity
})
export class AppModule { }
Listing 2-5

Root Module for the Application

App Component (Root Component)

An app component is a set of files that render the first file and the root component of the application. An upcoming chapter discusses these components in detail.

The following are the files.

    •  src/app/app.component.ts: The component’s TypeScript code file.

    •  src/app/app.component.spec.ts: The component’s unit test file.

    •  src/app/app.component.css: The component’s style sheet.

    •  src/app/app.component.html: The component’s view template. It contains HTML markup and handles presentation for the component.

Routing Module: app-routing.module.ts

src/app/app-routing.module.ts is a module file. Angular CLI generates it only if routing is selected when creating the project. The purpose of this module is to encapsulate routing logic into its own Angular module.

This module is referenced and imported into the main module of the application. In Listing 2-6, the routing module class is available in the main module, and it needs to be imported into JavaScript first (see line 2). Then, it is imported into NgModule (Angular module) (see lines 5, 6, and 7).
1. // Import routing module (JavaScript import)
2. import { AppRoutingModule } from './app-routing.module';
3. // Import it into Angular module
4. @NgModule({
5. imports: [
6.   AppRoutingModule,
7.],
8. // Code removed for brevity
9. })
10. export class AppModule { }
Listing 2-6

Import Router Module

Scripts

Consider the following scripts in package.json for primary tasks working with an Angular application. These are created using Angular CLI.

Start Script

To run the start script, use
yarn start
or
npm start

Refer to the start script in package.json. The start script runs the Angular CLI ng serve command. We can run ng serve directly; however, it is a general practice to run the application using the start script. It is a common convention for Node developers to run the start script to start an application.

The ng serve command depends on the configuration in angular.json to start the application. Refer to Figure 2-5 for the configuration to run the application with the script.
../images/475625_1_En_2_Chapter/475625_1_En_2_Fig5_HTML.jpg
Figure 2-5

Angular CLI configuration for ng serve command (run by script run)

The build Script

The build script compiles, bundles, and copies resultant files in a dist folder at the root of the project. The angular application output of this command is ready to be deployed on a web server. Consider the following commands to build the application.
yarn run build
or
npm run build
Figure 2-6 has “build” listed as one of the scripts. It runs the Angular CLI ng build command. Angular CLI uses the configuration in the angular.json file to build the application. It uses the following information from the configuration file. These are some of the many configuration items in the Angular CLI build process.
  • The destination directory in which to place bundled files

  • The main file for the Angular application that bootstraps the application

  • The index HTML file that loads the Angular JavaScript application

  • The TypeScript configuration

  • The polyfill configuration used for the application’s backward-compatibility requirements

  • The assets, such as images and icons, that the application needs

  • The style sheets that the application needs

../images/475625_1_En_2_Chapter/475625_1_En_2_Fig6_HTML.jpg
Figure 2-6

The build command configuration and output

See Figure 2-6 for the following.
  • The build script output in the terminal

  • Angular CLI configuration for the build command in the open file

  • Output files resulted by the build script (in the left nav)

The categories of the files generated are as follows.
  • index.html, the start file of the application

  • main.js bundled application

  • Other JS files are dependencies that the application needs to run.

  • Map files help with the debug process

  • The ico file at this stage in the application; however, it copies any images available in the assets

The JavaScript file generated is compiled and bundled; however, it is not minified. There are also additional map files for debugging; hence, this build script is not yet optimized for production deployment. Preferably, it would be used in a development environment deployment, which is an integrated environment with dependent external services yet developer-friendly with debug features.

To get a production-optimized build of the application, run one of the following commands.
yarn run build --prod
or
npm run build --prod

The production-optimized code is minified (a lower JavaScript file size), without map files for debugging and tree shaken.

The lint Script

Linting helps you to maintain coding standards and conventions in an Angular project. It warns developers about common mistakes with coding standards, naming, formatting, and so forth.

Use one of the following commands to run the lint script.
yarn run lint
or
npm run lint

Angular CLI runs the TypeScript lint process (tslint) with the command. As with the preceding two scripts, the Angular CLI configuration for the lint script begins with angular.json; however, the configuration for tslint is in tslint.json. The angular.json configuration leads to the TypeScript configuration, which in turn leads to tslint.json

Figure 2-7 shows the lint script result.
../images/475625_1_En_2_Chapter/475625_1_En_2_Fig7_HTML.jpg
Figure 2-7

The lint script result

Conclusion

This chapter provided instructions on getting started with an Angular application using TypeScript and Material Design. The chapter listed the prerequisites and provided installation instructions.

The chapter described the storyline for the sample application that will be used in all the upcoming concepts.

I prefer to use Angular CLI to build the Angular application. It describes the files and folders generated with CLI. It also describes the pregenerated scripts to perform JavaScript tasks.

Exercise

Create a new Angular application and include an Angular Material reference. Start the application and ensure that a pre-created welcome page comes up.

When the application is up and running on a browser, remove the content from the main component template. Ensure that the application automatically compiles successfully, and refresh the web page.

On the main component (app component), add a toolbar with the title of your choice. Show four Material Design cards with unique content on each card.

References

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.4.239