-
Notifications
You must be signed in to change notification settings - Fork 2
First Things First
First Things First. Before we can start coding with Angular, there are some preparatory steps. Welcome back to Angular: Getting Started. In this module, we set up what we need to work with Angular.
A little preparation goes a long way toward a successful adventure.
Before we take that first step on our journey with Angular, we need to make some decisions, gather our tools, and get everything ready.
- Selecting a Language
- Selecting an Editor
- Setting up an Angular Application
- About Module
In this module, we'll evaluate several languages we could use to build an Angular application and select one. Once we've picked a language, we select an editor that fully supports development in that language. Then we set up the boilerplate code for an Angular application. And we'll talk about modules and what they mean in Angular. Let's get started.
When building Angular applications, we have many language choices available to us. First, some background. The JavaScript language specification standard is officially called ECMAScript, or ES.
Java Script Language Specification
- ECMAScript(ES)
- ES 3
- ES 5
- ES 2015 (formerly knows as ES6)
- Must be transpiled
Up until recently, the ES versions were defined by a sequential number. ES3 is supported by older browsers. ES5 is the version currently supported by most modern browsers. The ES6 specification was renamed ES2015. Most browsers don't yet support ES2015, so ES2015 code must first be transpiled to ES5. What does that mean? Code developed with ES2015 must be compiled by a tool that converts the ES2015 syntax to comparable ES5 syntax before the browser executes it.
That way, we as developers get the benefits of the new ES2015 productivity features and the browsers still get code they understand. Since Angular is a JavaScript library, we could use any of the many compile to JavaScript languages to build our Angular application. But the most common language choices for Angular include the ES5 version of JavaScript.
ES5 code runs in the browser today without transpilation, so no compile step is required. If we want to take advantage of some of the new ES2015 features to improve our productivity, such as classes, the let statement, and arrow syntax, we can write our Angular code using ES2015. We then transpile our code to ES5 before running it.
ES5
- Runs in the browser
- No compile required
ES 2015
- Lots of new features (class, let, arrow etc)
TypeScript
- Superset of Javascript
- Strong typing
- Great IDE tooling
Dart
- No Javascript
Another language option is TypeScript. TypeScript is a superset of JavaScript and must be transpiled. One of the key benefits of TypeScript is its strong typing, meaning that everything has a data type. Because of this strong typing, TypeScript has great tooling including inline documentation, syntax checking, code navigation, and advanced refactorings. So TypeScript helps us better reason about our code.
The Angular team itself takes advantage of these benefits and uses TypeScript to build Angular. Most of the demo code in the Angular documentation also uses TypeScript. For these reasons, TypeScript is the language of choice for many Angular developers, and is the language we use in this tutorial.
Dart is another option. It is a non-JavaScript based language for building Angular applications. Because we'll use TypeScript throughout this tutorial, let's take a moment to look at what TypeScript is all about.
What is Type Script?
- Open source language
- Superset of JavaScript
- Transpiles to plain Javascript
- Strongly typed
- TypeScript type definition files (*.d.ts)
- Class-based object-orientation
- TypeScript is an open source language that is a superset of JavaScript and compiles to plain JavaScript through transpilation.
- It is strongly typed, so every variable, every function, and every function parameter can have a data type. - - How does TypeScript determine the appropriate types when using JavaScript libraries that are not strongly typed? By using TypeScript type definition files. These files contain the definition of each type in a library. These files are named with a library name, .d.ts.
- TypeScript implements the ES2015 class-based object orientation, plus more. It implements classes, interfaces, and inheritance. So if you have experience with an object-oriented programming language such as C#, C++ or Java, using TypeScript may feel very natural to you.
This tutorial does not require any prior knowledge of TypeScript. I'll cover what you need as you need it. But if you want to learn more about TypeScript, check out the TypeScript playground. This website allows you to do live coding with TypeScript, see the transpiled JavaScript, and run the result, all without installing anything. There are also several TypeScript tutorials including TypeScript Fundamentals, AngularJS with TypeScript, which walks through using TypeScript with AngularJS, and using ES6 with TypeScript, which details all of the new ES2015 features such as let and arrow syntax. Again, you do not have to know TypeScript for this tutorial. We'll learn it as we go. Now that we've selected TypeScript as our Angular language, let's pick an appropriate code editor.
There are many editors that fully support TypeScript, either out of the box or with a plugin, including all of these.
- Visual Studio
- Visual Studio Code
- Web Storm
- Atom
- Eclipse
- Others
Select one of these, or whichever editor suits you best. But keep in mind that your experience with TypeScript will be much more pleasurable if you select an editor that understands TypeScript. For this tutorial, I am using Visual Studio Code. Visual Studio Code runs in Linux, Windows, and OS X. It has great features that support TypeScript, such as auto-completion, IntelliSense, syntax checking, and refactorings. If you want to use VS Code as your editor, you can download and install it from this URL. If you are interested in using Visual Studio Code and want to learn more, check out their website. But you are free to use whichever editor you choose. Now that we've picked a language and selected and installed an editor, let's set up our environment.
Setting up our development environment requires two basic steps.
- Install npm, or Node package manager, and
- Set up the Angular application.
There is no need to manually install Angular or TypeScript or any other library. However, this step two is really quite a process.
But, first things first, what is npm?
npm
- Node Package Manager - Package manager for JavaScript
- Command line utility
- Install libraries, packages, and applications
- https://node.js.org/en/download
Npm, or Node package manager, is a command line utility that interacts with a repository of open-source projects. Npm has become the package manager for JavaScript. Using npm we can install libraries, packages, and applications, along with their dependencies.
We'll need npm to install all of the libraries for Angular and to execute scripts to transpile our code and launch our Angular application.
If you don't already have npm, you can download it from this link. Let's take a look. Following that link takes us to the download page for Node, which installs npm. Angular minimally requires this(>= 5.5.1) version of npm. Then select the installer appropriate for your OS. Feel free to pause the tutorial here and install npm now, if you don't already have it. With npm installed, we are ready to set up our Angular application.
Depending on the tools you select, setting up an Angular application could be somewhat laborious. Before we begin, let's list the required steps, then we'll look at ways to set up Angular without actually performing these steps.
To manually set up an Angular application:
- We'd need to create an application folder
- Add package definition and configuration files
- Install the packages
- Create the application's root Angular module because every Angular application needs at least one Angular module,
- Create the main.ts file to load that Angular module
- Create the host web page, normally index.html.
Luckily, we have some options. We could manually perform each of these steps, though it would be time consuming and prone to error, so this option is not recommended.
Alternatively, we could use tooling, such as the Angular CLI. The Angular CLI is a command line tool for generating the set of files and boilerplate code for an Angular application. The CLI also generates your component's modules, services, and other files. It scaffolds and executes your unit in end-to-end tests, and provides options to minimize package and prepare the files you need for deployment. The Angular CLI can be found here. The CLI is the recommended tool for building, testing, and deploying Angular applications.
We'll look more at the CLI later in this tutorial. However, to code along with this tutorial, I recommend that you instead download the simple application starter files. These files are available in my GitHub repository. I used the Angular CLI to create these files, but then included some extra files we'll need as we build our sample application throughout this tutorial. Let's go with this last option. I've navigated to my GitHub repository following the URL from the slide. If you are comfortable with Git, you can clone this repository. Otherwise click this button to download all of the files as a single zip file. The APM - Final folder contains the completed code for our sample application. Use these files if you want to see the end result. The APM - Start folder contains the starter files. These are the files we will use as the starting point for building our Angular application. After downloading the files, copy or extract the files in the APM - Start folder to a working directory called just APM. Your APM folder should then look like this. Now let's open the APM folder with a code editor.
I've opened the APM working folder with VS Code. First, let's talk about the directory structure.
By convention, all of our source files are under a folder called src. Under that folder is an app folder that contains the source files specific for our application. We only have a few folders and files here now, but we'll add more as we progress through this tutorial.
For applications of any size, we'll have subfolders under the app folder for each major feature in the application. The other files here are configuration and setup files, often called boilerplate files
.
To get us going quickly, we won't dive in to all of these files now. We'll learn more about them in the Building, Testing, and Deploying with the CLI module later in this tutorial.
Before we can execute this code, we need to install all of the libraries required to develop and run our application. Where are those defined? In the package.json file here. This file contains a list of all of the application's dependencies.
The @angular entries are Angular system libraries. Down here are some additional dependencies that are only required for development. This is where TypeScript is defined. Toward the top of this file is a set of scripts. We can execute these scripts using npm. We'll learn more about these scripts throughout this tutorial.
For now, let's install all of these libraries. First open a command prompt or terminal. VS Code has an integrated terminal we can use. View, Terminal. Next, navigate to the folder containing the package.json file. VS Code did that for us. Before we continue, let's check the version of npm by typing npm -v
.
Adarsh:APM-Start adarshmaurya$ npm -v
6.4.1
Adarsh:APM-Start adarshmaurya$
Angular minimally requires this(>=5.5.1) version of npm. If required, update your npm before proceeding. Then type npm install
. This installs all of the dependencies defined in the package.json
file, along with any of their dependencies. Note that you may see some warnings and messages during this installation process, like these. In most cases you can ignore them.
Adarsh:APM-Start adarshmaurya$ npm install
> fsevents@1.2.4 install /Users/adarshmaurya/Playground/getting-started-angular/APM-Start/node_modules/fsevents
> node install
[fsevents] Success: "/Users/adarshmaurya/Playground/getting-started-angular/APM-Start/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node" already installed
Pass --update-binary to reinstall or --build-from-source to recompile
> node-sass@4.9.3 install /Users/adarshmaurya/Playground/getting-started-angular/APM-Start/node_modules/node-sass
> node scripts/install.js
Cached binary found at /Users/adarshmaurya/.npm/node-sass/4.9.3/darwin-x64-64_binding.node
> node-sass@4.9.3 postinstall /Users/adarshmaurya/Playground/getting-started-angular/APM-Start/node_modules/node-sass
> node scripts/build.js
Binary found at /Users/adarshmaurya/Playground/getting-started-angular/APM-Start/node_modules/node-sass/vendor/darwin-x64-64/binding.node
Testing binary
Binary is fine
added 1166 packages from 1172 contributors and audited 39128 packages in 15.47s
found 0 vulnerabilities
╭───────────────────────────────────────────────────────────────╮
│ │
│ New minor version of npm available! 6.4.1 → 6.5.0 │
│ Changelog: https://github.com/npm/cli/releases/tag/v6.5.0 │
│ Run npm install -g npm to update! │
│ │
╰───────────────────────────────────────────────────────────────╯
Adarsh:APM-Start adarshmaurya$
If you see something like this at the end, the installation completed successfully. Notice that we now have a node_modules folder here. This is where npm installed all of our libraries. This folder is large, so you may want to exclude it when you check your files in to a source control system. Now that we have everything installed, let's try running the sample application.
I've included enough additional code with the starter files to run the sample application, so let's give it a try. Remember the scripts area in our package.json file?
Here is the start script. When we type npm start
, it will execute the command defined here. The ng executes the Angular CLI. The string after the ng is the CLI command. The serve command builds the application and starts a web server. The -o is a command option that opens the URL in our default browser.
The CLI has many more commands and options, we'll see more of them as we progress through this tutorial.
Are we ready to make it go? Let's try out this start script.
Adarsh:APM-Start adarshmaurya$ npm start
> apm@0.0.0 start /Users/adarshmaurya/Playground/getting-started-angular/APM-Start
> ng serve -o
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2018-12-10T23:04:15.350Z
Hash: 7b6d693eac46710eb2ab
Time: 5395ms
chunk {main} main.js, main.js.map (main) 9.84 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 223 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 16.6 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.31 MB [initial] [rendered]
ℹ 「wdm」: Compiled successfully.
Back at the command prompt or terminal, type npm start
. This executes the start script, builds the application, starts a web server, and opens the URL in the default browser, which in my case is Chrome. If all is well, the application appears in the browser and displays some text as shown here.
localhost:4200
Welcome to Angular: Getting Started!!
...Starter Files...
If the text does not appear, or you see errors in the console, ensure that you ran npm install successfully as defined in the prior clip. As you can, see our application doesn't look like much, but we'll fix that on our journey through Angular.
Let's see what happens when we make a code change. In the editor, open the app.component.html file. Don't worry too much about the syntax here yet, we'll talk about it shortly. For now, we'll just change the welcome text. We immediately see here that our code is recompiled, the browser refreshes, and our updated text appears. So any time we make a change to our application, we'll be able to immediately see the effect of that change. That will be helpful. When we are finished working with our files, we can close the browser, but the server keeps running. To stop it, go back to the command prompt or terminal and press Ctrl+C or Command+C and y for yes, then you can exit.
Any time you want to run the application and keep it running to watch the effect of your code changes, simply open the terminal and use npm start
again. So now we know how to build and run our code. Yay! You may have noticed that I didn't save the file after I made the code change. When using VS Code, we can set it to automatically save our changes. Here under File, Preferences, Settings, Workspace Settings, I have it set to automatically save after a short delay. Before we go any further, let's take a moment and talk about modules.
With JavaScript, there's always the problem of namespaces
. If we are not careful, we can easily end up with variables or functions in the global
namespace. In addition, JavaScript didn't provide features to help with code organization.
Modules help resolve these issues.
Namespaces Modules Code Organization
- AngularJS Modules
- TypeScript Modules
- ES 2015 Modules
- Angular Modules
AngularJS has modules to help us organize our code and resolve some name spacing issues. TypeScript also has modules that help keep things out of the global namespace. ES2015 set a standard for defining a module.
- In ES2015, a module is a file, and a file is a module, so when coding in ES2015, we don't need to define or name modules, just create a file, write some code, export or import something, and bang, the file becomes a module.
- Angular leverages ES2015 modules, so as we create code files and import or export something, we create the modules for our application. But wait, there's more. Angular also has Angular modules. Angular modules are separate and different from Angular's implementation of ES2015 modules.
Let's look first at how Angular makes use of ES2015 modules, then we'll introduce Angular modules.
How do ES2015 modules work?
Say we create a code file called product.ts and export a class named Product from that file. This file then becomes a module.
Export
--- product.ts ---------- Compile ---product.js--------
| export class Product{ |============} | function Product(){ |
| | | } |
| } |============} | |
------------------------- Transpile ---------------------
Because the class is exported, we can use that class and any other module by importing it.
Import
--- product-list.ts -----
| import {Product } fro |
| './product' |
-------------------------
So here we have a file called product-list.ts and we import our Product class. This file also becomes a module because we imported something. Notice the syntax here. In curly braces, we define the name we want to import, in this case Product, and we define the file we want to import it from. Here we want to import from product.js.
Wait, what? The product class is in product.ts, but when we compile, the TypeScript file is transpiled into an ES5 JavaScript file, so at runtime, we are importing from the .js file, but notice that we don't list the extension here anyway.
Now let's look at Angular modules. Angular modules help organize an application into cohesive blocks of functionality.
Angular Modules
Root Angular Module <--- Feature Angular Module <--- Shared Module
| | |
| | |
Component Component Component
| |
Component Component
Every Angular application, has at least one Angular module, by convention called app module
.
As an application gets more features, we can group those features into their own feature modules
.
We can even define shared or common modules for code used by multiple Angular modules.
This keeps the code organized and provides a cohesive unit we can load on start, or lazy load as it is needed.
In each Angular module, we declare the set of components and other code files associated with the module, and the dependencies needed by those components.
Each component we create is declared in and belongs to one and only one Angular module. We'll talk much more about Angular modules throughout this tutorial.
Let's clarify the difference between ES2015 modules and Angular modules.
ES Modules
1. Code files that import or export something
2. Organize our code files
3. Modularize our code
4. Promote code reuse
Angular Modules
1. Code files that organize the application into cohesive block of functionality
2. Organize our application
3. Modularize our application
4. Promote application boundaries
ES modules are code files that import or export something. Angular modules are code files that organize the application into cohesive blocks of functionality. ES modules organize our code files. Angular modules organize our application. ES modules modularize our code. Angular modules modularize our application. ES modules promote code reuse. Angular modules promote boundaries within our application, so ES modules are about code files, and Angular modules are about our application.
To keep these terms straight, I'll refer to the ES2015 modules as ES modules and Angular modules as Angular modules.
- Selecting a Language
- Selecting an Editor
- Setting up an Angular Application - npm
- About Modules
- In this module, we discussed several languages and selected TypeScript. TypeScript has all of the productivity features of ES 2015 plus strong typing for better tooling.
- We then selected an editor. Which editor you use for TypeScript is a personal preference. For the best experience, be sure your selected editor fully supports TypeScript.
- We then installed npm and looked at the laborious process required to manually set up the boilerplate code for an Angular application. Instead of manually setting this up, we downloaded the starter files for my GitHub repository. We then saw how to install, run, and edit the sample application.
- We covered ES modules and how TypeScript uses ES module syntax to export and import functionality from our ES modules. We introduced Angular modules and how they organize our application and promote application boundaries.
- We call the architecture for the sample application that we are building that we outlined in the first module.
Application Architecture
-> Welcome Component
|
index.html -> App Component->|-> Product List Component ---
| | | --> Star Component
| V |
-> Product Detail Component---
Product Data
Service
Since I used the Angular CLI to create the starter files, it created the index.html file and our root app component. In the next module, we'll examine these files and start writing some Angular code.