February 2017

Volume 32 Number 2

[The Working Programmer]

How To Be MEAN: Working the Angular

By Ted Neward | February 2017

Ted NewardWelcome back, MEANers. As mentioned last month, it’s time to start working the front end of the MEAN stack, which means diving into Angular. As of this writing (and probably for the next couple of years), that presents a problem—Angular has a bit of an identity problem. Angular has been the staple of the Single-Page Application world for many years. However, as Angular developed, it grew into a different architectural paradigm, and as a result, the “modern” Angular grew to become backward-incompatible with Angular.

That leaves most developers with the thorny question: Which version to use?

While there’s never a one-size-fits-all answer to the problem, history has shown that with only a few exceptions, the later version eventually wins out. This leads to a basic rule of thumb: If you’re just starting to work on the project (a so-called “greenfield” project), and there’s no existing code to maintain or extend, then use the latest-and-greatest stable version of the framework. Because my application (the tiny speaker ratings portal that I’ve been toying around with) definitely falls under the category of greenfield, that means that within the pages of this column series, I’ll use Angular 2 for the modern version of Angular and Angular 1 for the original product.

Yes, the decision could have easily gone the other way. Fortunately, the Internet holds dozens of good Angular tutorials (and good on ya, mate, if you choose Angular 1 for keeping all those Angular 1 tutorial writers happy). However, be warned that “porting” an Angular 1 app to Angular 2 looks to be more of a complete rewrite, so be sure to take that into consideration in future plans.

Meanwhile, we have some Angular 2 to explore.

Getting Started

The first step in working with any new technology is to write the ubiquitous “Hello World” for it. Two interesting things emerge immediately, though, when looking to do an Angular 2 “Hello World” app that bear discussing before going too far into the process.

First, with a Web framework like Angular, usually the installation process is almost ridiculously lightweight (compared to installing new programming languages, IDEs, databases and so on), because most of the time the actual library itself can be fetched directly out of a CDN or from the host server. However, for most development tasks, it’s better to have the library running off the local filesystem, and because that’s the default way to get started with Angular 2, that’s the path I’ll take.

Second, Angular 2 chooses to make its debut through a Git repository—in other words, the default “getting started” approach is to clone an existing Git repository on GitHub, as opposed to an IDE-hosted “project template.” This is an approach that’s starting to gain steam with other languages and other frameworks. It has the distinct advantage of being easy to understand, is trivial to maintain and (perhaps most important) is simple to extend to include additional features (structure, contents and so on) that the original template doesn’t have.

Thus, assuming Node.js is installed on your machine (which it should be for readers who’ve been following along in this series), getting the Angular 2 “quickstart” project is a Git request:

git clone https://github.com/angular/quickstart.git hello

Assuming this connects to GitHub and successfully clones the project, a ton of files now rest in the “hello” subdirectory. There are far more, in fact, than would seem absolutely necessary for a simple “Hello World” application, and the Angular team admits as much. In the repository’s README file, they specifically state that they’re laying out a number of additional files to promote some good habits right from the beginning, such as unit and end-to-end (e2e) testing of the front-end code.

Examining much of that will come later. For now, a glance through the directory will reveal a couple of things that should be familiar to MEANers: package.json (the npm manifest file) and tsconfig.json (the TypeScript configuration file) stand out immediately. Recall that the standard practice when pulling a Node.js project out of source control is to boot strap the dependencies into place, so before doing anything else, pull down the dependencies and give the project a wake-up call by executing the following, then browse to port 3000 in a browser (Actually, the script will usually open one for you once a local HTTP server is running on that port.):

npm install

npm start

Then, bask in the warm greetings of a Web framework, as shown in Figure 1.

Hello Angular 2 Web Framework
Figure 1 Hello Angular 2 Web Framework

In and of itself, it’s always nice to know that everything works, but programmers want to see code. Head back to the command-line shell that’s running the HTTP server and hit Ctrl+C to shut everything down. (Alternatively, open a second command-line shell to the same directory, whichever is easier.)

Let’s take a look, shall we?

Hello, Code

Of course the first place you can look to find code in an Angular 2 application is the index.html file, but this is actually going to be a little more confusing than helpful right now; for the moment, let’s leave it alone and dig around elsewhere.

The Angular team will be the first to admit that the directory structure of the Quickstart isn’t designed to be a prescriptive guide on how to structure code, but usually all Angular 2 apps will have some sort of “source” directory in which the application resides off the main root of the project. (This makes it much easier to bundle up without pulling in all sorts of developer-only files, such as package.json.) In the Quickstart, this directory is called “app,” and it contains three files: main.ts and two files that seem closely related—app.component.ts and app.module.ts. (Note that the TypeScript transpiler will modify these files in-place, so the directory might contain more than just these files, but it’ll be a little obvious that they’re all related—for example, main.ts will generate main.js and main.js.map). The first, main.ts, is clear as to its purpose—it’s the main entry point for the Angular 2 application—but the other two are a little less so. Nevertheless, let’s look at all three.

Entry Point: Main.ts

The contents of main.ts are a little cryptic at first:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

That’s not exactly clear. However, let’s take it piece by piece. You know from my last column on TypeScript that the “import” statement pulls in symbols from another file, and you can see that it’s importing symbols from two different places. The first, platformBrowserDynamic, is coming from somewhere in the Angular libraries, so this is probably standard boilerplate to boot strap the Angular 2 environment and library. (The last line definitely bears this out.) The second, however, imports from a local file, app.module, which sounds suspiciously like it’s supposed to contain your code.

For the most part, main.ts remains untouched throughout Angular 2 development with anything application-related at least living in the module file (app.module.ts), but it’s always useful to understand the context. (Although it’s not recommended at this point, if you follow the trail from index.html, you’ll eventually find where main.js gets loaded through the System.js module-loader mechanism.) That means, then, that most of the action takes place in app.module and its relations.

The Application Module: App.module.ts

Like its predecessor, Angular 2 cares a great deal about modularizing the application code into manageable bite-size chunks, and the first step to doing that is to put application-wide elements into a single place, which in Angular 2 speak is a module. Hence, this file will pull in a few Angular 2 concepts and then declare the application module and what it, in turn, uses:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
export class AppModule { }

Again, for the moment, this primarily is all import statements: First, pulling in some Angular 2-related materials (NgModule and BrowserModule), then importing an application component, which I’ll touch on in a second. Notice, however, that NgModule is (as discussed in my last column) a TypeScript decorator—in essence, this is what lets Angular 2 have all the functionality it’s expecting while letting developers use the framework to stay focused on just the application-specific features on the application-specific class (which is called AppModule here).

It’s actually quite important to understand that Angular 2 takes a strong stance on the segregation of code and features into modules and components. This will be a theme that’s repeated over and over again in Angular 2, whereas in Angular 1 it was possible to think about code being arranged more or less in whatever manner the developer chooses (or, more often than not, chooses not to organize at all). In Angular 2 the library forces developers to face the organization scheme right away. Angular 2 lets you choose the granularity of your modules and components to be as large or as small as you like, but you must organize them into modules and components, without question. This is simply “The Angular Way,” and you must follow the process.

The NgModule decorator provides metadata about this module, including what other modules it depends on, what declarations it exports (which you’ll see used in a second) and what bootstrapping needs to take place. NgModule has several options that you can pass here, and as an Angular 2 application grows in complexity, these lists grow. Bookmark this file some place as you’ll be back here often.

A Hello World Component: App.component.ts

The last bit to discuss is the actual application component—the only one, so far—that defines the UI (all one line of it, anyway). This is the app.component.ts file:

import { Component } from '@angular/core';
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`,
export class AppComponent  { name = 'Angular'; }

Again, the component depends on an Angular 2 construct—the Component decorator—so it imports it from the appropriate place inside the Angular libraries. It then declares an exported class, called AppComponent, to be an Angular component, with two parameters: a selector and a template. The template is straight­forward: This is the HTML snippet applied where this component is declared (complete with ECMAScript string interpolation binding, in this case for the “name” parameter in the HTML). Because this template can sometimes get to be a bit large, or at least larger, than the single line of HTML defined here, instead of “template” you can also use templateUrl to specify an external file in which to find the template, which you’ll do in later incarnations.

The selector parameter is a bit more subtle; it declares where in the UI this component is to apply. Practically speaking, this means that anywhere a my-app tag shows up in HTML, this component is applied instead. You haven’t seen any <my-app> tags thus far, but that’s simply because this particular tag is declared inside of the index.html file (which I haven’t discussed):

<!DOCTYPE html>
    <title>Angular QuickStart</title>
    <!-- bunch of other stuff snipped for simplicity -->
    <my-app>Loading AppComponent content here ...</my-app>

Notice how my-app tag surrounds some text; this primarily is placeholder text that might or might not appear, depending on how quickly the browser loads and renders the application.

Wrapping Up

This has been a lot of work for a simple “Hello World”; it would seem a lot easier to simply write straight HTML and leave out the rest of it. However, a large part of “The Angular Way” is to build the application out of components, rather than just to sling HTML and CSS and JS everywhere, and that kind of organization and structure carries overhead with it. In fact, almost 90 percent of what I’ve discussed so far is essentially Angular overhead. As the application scales up in size, the overhead will proportionally shrink, and leave application developers to focus entirely on the “meat” of their application. And that’s exactly what an application framework is supposed to do.

Naturally, however, we’re not done yet. There’s a lot more of Angular 2 to explore, and we have a barebones application to build, to boot. In future columns, I’ll explore creating components, specifically doing some basic CRUD around the list of speakers (using an in-memory “database” to start), and how Angular 2 can make it simple to keep everything straight. Hang tight; much more is yet to come. Until then, happy coding!

Ted Neward is a Seattle-based polytechnology consultant, speaker and mentor. He has written more than 100 articles, is an F #MVP, has authored and coauthored a dozen books. Reach him at ted@tedneward.com if you’re interested in having him come work with your team, or read his blog at blogs.tedneward.com.

Thanks to the following technical expert for reviewing this article: Ward Bell

Discuss this article in the MSDN Magazine forum