Introduction to Angular

In this tutorial, we will build a Hello World style Angular component. The key focus is to learn how to install all the required software, create a very simple application and use it from a browser. We won't get too deep into Angular at this point.

Before you start working on this tutorial, please install the required software as mentioned in the Set Up Guide here .

Part 1 - Install Angular CLI

Angular Command Line Interface (CLI) is an indispensable tool for Angular development. It can create a project, generate artifacts like components and build your project. We will now install Angular CLI.

1. First, run these commands to make sure Node.js is installed correctly. Open a command prompt window and enter:

node --version

npm --version

Note: Node.js is only required in the development and build machines. We need it to install required packages and for Angular CLI to work. You don't need Node.js in a production machine.

2. Run this command to install Angular CLI.

npm install -g @angular/cli@7.0.3

Note, we used the global (-g) option to install the tool in a central location. This will let us run ng (the CLI command) from anywhere.

3. It should take a few minutes to install the tool. After installation finishes enter this command to verify everything is OK.

ng --version

Part 2 - Create a Project

Angular needs a lot of boiler plate code even for the simplest of projects. Fortunately, Angular CLI can generate most of this code for us.

1. Create a folder 'C:\LabWork' on your machine. This is where you will develop code for various labs.

2. Open a new command prompt. Switch to the C:\LabWork folder.

3. Run this command to create a new project called hello.

ng new hello --defaults

4. The project's directory structure should look like this at this point:

C:\LabWork\hello
└───src
    ├───app
    ├───assets
    └───environments

We are not quite ready to run this project. Before we do that, let's get to know more about the boiler plate code that is given to you.

Part 3 - The Anatomy of a Simple Angular Project

The Angular framework is released as several separate Node.js packages. For example, common, core, http, router etc. In addition, Angular depends on third party projects such as rxjs and zone.js. Manually downloading these modules can be cumbersome and error prone. This is why we use Node Package Manager (NPM) to download them.

You can use your favorite editor to edit code during these labs. For your convenience we have included the Visual Studio Code editor from Microsoft which is free to downloaded and use. VS Code is written in TypeScript and has out of the box support for that language which makes a great free editor for Angular development.

1. Open package.json from the hello folder in an editor.

This file declares the packages we have dependency on. Specifically, the dependencies property lists packages that we need at compile and runtime. The devDependencies section lists packages that we need for certain development tasks. You will see typescript listed there. We need this to be able to compile our TS code into JS.

2. In a command prompt window go to the C:\LabWork\hello directory.

cd C:\LabWork\hello

3. Run the following command to list the installed packages.

npm list --depth=0

4. You will see some errors but scroll up and verify you get something like this

hello@0.0.0 C:\LabWork\hello
+-- @angular-devkit/build-angular@0.10.3
+-- @angular/animations@7.0.2
+-- @angular/cli@7.0.3
+-- @angular/common@7.0.2
+-- @angular/compiler@7.0.2
+-- @angular/compiler-cli@7.0.2
...

The ng new command has run NPM and installed these packages for us already.


5. These packages are physically located inside the node_modules folder. Have a quick look in the folder.

Next, we will look at the source code of the generated project. We have not covered much of TypeScript or Angular yet, so do not worry too much about the details. There will be plenty of more labs to learn the details.

6. Open the component class hello/src/app/app.component.ts in an editor.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'hello';
}

The import statement tells the compiler that the name "Component" is available from the @angular/core module. Which means we can now start using the "Component" name for its intended purpose, which may be anything from a class name to a variable name. In this particular case "Component" is a decorator. By using the decorator with the AppComponent class, we are saying that AppComponent is an Angular component.

We are also adding a few meta data elements to the decorator. The selector property declares the HTML tag for the component. The templateUrl property points to the HTML template of the component.

What is a Component?
A component is a TypeScript class that is responsible for displaying data to the user and collecting input from the user.Every Angular application has one main component. This is displayed first to the user when the application launches. Our AppComponent class here is such a main component. We will soon see how we display it to the user by bootstrapping it.

7. Briefly look at the app.component.html file. This is the template code of AppComponent. A template is used to dynamically generate HTML in the browser. It looks like a regular HTML. But then it has things like this:

  <h1>
    Welcome to {{ title }}!
  </h1>

That {{ title }} piece will render the current value of the title variable of the AppComponent class instance.

Templates may look like plain HTML, but they actually get compiled into code. This is necessary for the template to dynamically display data and contain other display logic.

8. Next open the application module file hello/src/app/app.module.ts.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 import { AppComponent } from './app.component';

@NgModule({
  declarations: ,
  imports: ,
  providers: [],
  bootstrap: 
})
export class AppModule { }

An Angular module is a collection of components, services, directives etc. You can loosely think of it like a Java JAR file or a C++ DLL. Every application must have a root level module called application module. Our AppModule class is such an application module.

Every component that is a member of a module must be listed in the declarations array.

The main component of the application must also be listed in the bootstrap array.

9. Next open hello/src/main.ts. This file bootstraps or attaches the application mule tood the browser.

import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; ... platformBrowserDynamic().bootstrapModule(AppModule)   .catch(err => console.log(err));

When the AppModule is bootstrapped, Angular goes through index.html and looks for the selectors for the bootstrappable components in the module. If found, an instance of the component is then inserted into the DOM of index.html where the matching selector is located. In this case AppComponent is displayed inside the index.html page wherever the "my-app" tag appears.

Did You Know?
Here we are bootstrapping our application module into the browser. But Angular can also be used to write native mobile applications for Android and iOS. In that case, we will use something else other than  platformBrowserDynamic() to bring the module into display.

10. Finally, open hello/src/index.html.

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Hello</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>

When the AppModule is bootstrapped the DOM tree generated by the template of AppComponent will be inserted where <app-root></app-root> appears.

Notice that no Java Script files are currently imported into the index.html. How does our code get loaded into the browser? All such dependencies will be added into the index.html file by the build process.

Part 4 - Run the Development Server.

During development you should access your Angular application site using the Angular CLI provided web server. It has many benefits. Among which are:

  • Rapidly rebuild the application when you modify any file.

  • Automatically refresh the browser after build finishes.

1. From the command prompt go to the root folder of our project C:\LabWork\hello.

2. Run this command to compile TypeScript.

npm start

Alternatively you could also enter ng serve. But npm start has an advantage. It lets you specify extra arguments to ng serve in package.json. It's better to get used using npm start.

This will compile the TypeScript files and start the development server:

chunk {main} main.js, main.js.map (main) 10.7 kB  
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 227 kB  
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB  
chunk {styles} styles.js, styles.js.map (styles) 15.6 kB  
chunk {vendor} vendor.js, vendor.js.map (vendor) 3.39 MB  wdm: Compiled successfully.

Once this process is running, it will recompile TypeScript, rebundle the result and repost the bundles to the server every time file changes are saved.

3. Try loading the application by entering the following URL into the address bar of the Chrome browser.

http://localhost:4200/

You should see the following:

4. Leave the browser and the server running for the next section.

5. View the source code of the page. Notice that a bunch of <script> tags have been added at the end of the <body></body> element. These scripts include your own application code, Angular library code and anything else your application may depend on.

Part 5 - Change the Component Code

We will make a small change. You will see how the 'start' command will automatically recompile the code.

1. Open hello/src/app/app.component.ts in an editor.

2. Replace the 'title' property with a 'name' property. Give the 'name' property a value of 'Android'. When you are done the class portion of the file should look like this:

export class AppComponent {
 name = 'Goofy Goober';
}

3. Save changes.

4. Open app.component.html.

5. Delete the entire content of the file. Then enter this line:

<h1>I'm {{name}}</h1>

6. Save the file.

The component has some state in the form of a property called 'name'. It is rendering the value of this "name" variable in the HTML template using the {{name}} syntax. This is an example of one-way data binding where data is taken from the component and shown in DOM.

7. Back in the server command prompt, you should see messages about the code being recompiled and bundles being rendered.

Note: The 'npm start' command executes the 'ng serve' command which invokes the Angular build and deployment system. The system listens for file changes and makes sure that any TypeScript files that are changed are recompiled to JavaScript and included in one of the *.js bundles. These bundles are then made available through the development server. This all happens automatically so that any changes you make to the code will appear very quickly in the browser. If the code you added resulted in compile errors you will see those in the command prompt.



8. Go to the browser window and verify that the changes you made to the app appear. If everything went well you will see the following in your browser:

9. Let's clean up. First, close out the server by entering Ctrl-C in the command prompt window. Then close out the browser tab where you were viewing the application.

10. Close any open files and command prompt windows.

Part 6 - Review

Our goal in this lab was to take a look at a basic Angular application and go through the workflow of building and testing it.

First, we learned that our code is written in TypeScript which needs to be transpiled into JavaScript.

Next, we saw how a build system is used to:

  • Transpile TypeScript,

  • Create *.js bundle files for the app,

  • Serve the index.html and bundle files

Finally we accessed the application using a browser.

Karandeep Kaur June 25, 2019

Leave a Reply

Your email address will not be published. Required fields are marked *

Web age solutions blog Zones