Back our Angular 4 Book on Kickstarter.

Hello Angular 2 - Introduction to Angular 2 with JavaScript - Part 1

Angular 2 has officially been released. A while back I wrote a short series of articles that were an introduction to Angular 2. None of that code worked on the final release; so I'm revisiting them here.

Angular 2 still seems to have a documentation problem. Angular is built to be used by TypeScript, JavaScript, or Dart. However, only the TypeScript tutorials are fleshed out. Coming from an Angular 1 background with JavaScript, I wanted to start my Angular 2 adventures using JavaScript.

I'm writing this series of blog posts to show how I created my first Hello World Angular 2 application using JavaScript.

Import the Angular 2 libraries

One difference I noticed between Angular 1 and Angular 2 is that Angular 2 code base is split up among many different libraries. I believe this was intentional so you could easily remove components of Angular that you do not need; thus making the overall load time for your application smaller.

Let's look at a bunch of these:


<!-- IE required polyfill -->
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>

The first is a polyfill library for Internet Explorerer. Polyfill is a term for implementing an API not natively supported. Internet Explorer requires this to support promises and dynamic modules loading, as defined as part of the ECMAScript 2015 specification. Other browsers support this by default. You can leave this out if IE is not required for your application.


<script src="https://unpkg.com/zone.js@0.6.25?main=browser"></script>
<script src="https://unpkg.com/reflect-metadata@0.1.8"></script>

Zone and Reflect are the Polyfills used by AngularJS.


<script src="https://unpkg.com/rxjs@5.0.0-beta.12/bundles/Rx.js"></script>

Reactive Extensions RXJS is a library for composing asynchronous and event based programs using Observable collections. Observable collections are an implementation of the Observer design pattern. It is a way for one object to notify others of state changes. Data binding is an example of this. RXJS is used in many Angular 2 applications.

Finally, import the main Angular 2 libraries:


<script src="https://unpkg.com/@angular/core/bundles/core.umd.js"></script>
<script src="https://unpkg.com/@angular/common/bundles/common.umd.js"></script>
<script src="https://unpkg.com/@angular/compiler/bundles/compiler.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser/bundles/platform-browser.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"></script>

The official API reference contains detailed information of what each library is, but for the purposes of this article I decided not to go into details.

Create Your First Angular 2 Component

The first thing we'll do is create an Angular 2 component. The default Angular 2 method is to wrap the component around an Immediately Invoked Function Expression (IIFE) function, like this:


(function(app) {
})(window.app || (window.app = {}));

There is no Angular code in this snippet yet, but I want to point out that a variable is passed into the function. This is window.app, which is an object. Some shorthand trickery is used to define window.app as an empty object. The code could be rewritten like this:


window.app = {};
(function(app) {
})(window.app);

I find the approach of storing a pointer to the main application object curious. Global variable are sometimes considered bad practice and when building Angular 1 applications, I went out of my way to avoid creating new ones. Here we create one for the main Angular component.

Now, let's flesh out the component:


app.AppComponent = ng.core.Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
.Class({
constructor: function() {}
});

Inside the empty app object, a property named AppComponent is created. This creates an Angular component using the ng.core.Component() function. In Angular 2 a component seems to be synonymous with a directive in Angular 1. The Component() function accepts an object as its argument. The object has two properties. The first is the selector, which is the component name and how it will be referenced in HTML code. The second is the template, which is the HTML Text. For the purposes of this sample, I defined the template inline.

After the Component() function, you'll see the dot notation used to call a second method named Class(). This is where we define the JavaScript behind the component, sort of like a Controller in Angular 1. For the moment this component has no JavaScript. It is an entity that includes some markup and some JavaScript code. Angular 2 purposely separates the JavaScript and markup portions of the template.

Create the Angular Module

The next step to create a running AngularJS application is to create the Angular module. After the component is defined add another IIFE:


(function(app) {
})(window.app || (window.app = {}));

Then create the module:


app.AppModule = ng.core.NgModule({
imports: [ ng.platformBrowser.BrowserModule ],
declarations: [ app.AppComponent ],
bootstrap: [ app.AppComponent ]
})
.Class({
constructor: function() {}
});

The NgModule() function is called on the ng.core library. It operates similar to the Component() function; but this time creates an Angular app instead of an Angular component. For the purposes of this article, think of an app as a collection of components. A single array argument is passed into the NgModule() function; which is a list of configuration options. Chaining off the module creation, a class is create with a constructor. We are not putting anything in the class for the purposes of this sample.

The argument list in the NgModule() contains imports, declarations, and bootstrap. The imports define the other, external, modules that are required for this app. The declaration and bootstrap both refer to our custom components made for this application. In this case, they reference the app.AppComponent variable.

This is a switch from Angular 1 development, where in most cases you would define the module first, and all components, directives, and services later.

Bootstrap the Component

In Angular 2, you initialize an Angular module by bootstrapping it. This tells Angular 2 to examine the HTML; find any tags it recognizes, and replace them with the relevant HTML and JavaScript interaction. This statement is, once again, wrapped in an IIFE:


(function(app) {
})(window.app || (window.app = {}));

The IIFE's function accepts the window.app variable, and we use the same short-hand approach to define that variable if it is not yet defined. Next, add an event listener to the DOMContentLoaded event. DOMContentLoaded is a browser event that launches whenever the page is finished loading:


document.addEventListener('DOMContentLoaded', function() {
});

Inside the DOMContentLoaded event handler function, call the bootstrapModule() method on the platformBrowserDynamic object:


ng.platformBrowserDynamic.platformBrowserDynamic().bootstrapModule(app.AppModule);

Now, the JavaScript behind your first Angular 2 app is ready to go. The last step is to add some HTML.

Use Component in HTML

Inside the body of the HTML application, create an instance of the my-app component:


<my-app>Loading...</my-app>

Then you're app should be ready. Try to run it, you should see the loading message:

This message should go away quickly, to be replaced by the actual app:

You can play with this code here.

Final Thoughts

This sample isn't all that interesting yet. But, in the next entries in this series I'll take a look at how to implement binding in the application and how to respond to button clicks.

Get our Updated Intro to Angular 2 White Paper

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Katie Manning's Gravatar npmcdn.com
our entire site isn't loading because this element doesn't respond , how can we fix this?
# Posted By Katie Manning | 12/31/16 11:59 PM
Jeffry Houser's Gravatar @Katie Manning

It depends why the site isn't loading. You could get the libraries and store them locally. Or if a firewall is an issue; you could whitelist that site on your local firewalls.
# Posted By Jeffry Houser | 1/10/17 8:53 PM
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.