JavaScript
Article

Creating Components in Angular 2 with Typescript and ES5

By Thomas Greco

This article was peer reviewed by Stephan Max, Jeff Smith and Ravi Kiran. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

As the year draws to a close, the Angular team is closer than ever to releasing a stable version of Angular 2.0. This will reshape the way Angular applications are developed, but for the better. Throughout this article, I am going to show you some of the core concepts in Angular 2.0, and how they can be used. Specifically, I am going to take you through the process of building a component in Angular 2 from start to finish. First, we will take a detailed look at how this is done using TypeScript, then we will then migrate our Angular component, so that it works using plain ES5.

The code for this tutorial can be found on our GitHub repo. The repo has two branches, one for the TypeScript version and one for the ES5 version. If you want to clone a specific branch, use git clone <url> --branch <branch>.

What Is a Component?

The use of components in JavaScript has increased a tremendous amount over the past months. They are used in projects such as React, Knockout, Ember, and more, so it is no surprise that Angular has incorporated them into version 2.0. Code modularity has always been something that the Angular team has placed a focus on, and the use of components underlines this, as they allow us to break up our code into encapsulated pieces.

But what is a component? Well, it’s essentially a bit of code that can be re-used throughout an application. It consists of two things: a view, and some logic. By leveraging the focus that the Angular development team has placed on components, we can harness some pretty powerful functionality. Angular 2 makes it incredibly easy to create dynamic applications made up of different components, which have taken over from directives as the head-honcho of the framework. In Angular 2, directives are lightweight components, and they are simply used to append some functionality to the DOM. Now, Angular developers do not have to worry about messing up an application due to conflicting problems regarding isolate $scope. Instead, the use of components is a way of ensuring that our code from one section of an application will not interfere with that from another.

TypeScript

Angular 2.0 has been created to use TypeScript, which is a superset of JavaScript. The developers of Angular have spent a tremendous amount of time working towards this release. They have worked to optimize performance regarding both page speed, as well as work flow automation. TypeScript is similar to other code transpilers and allows developers to write code that can be easily converted to valid JavaScript. That being said, it has become increasingly popular, especially throughout the past year, so the Angular team decided to create the framework using it.

One of the benefits that comes from using TypeScript is its type system, which allows developers to annotate their JavaScript with type information. This annotated code is run through a compiler which helps catch errors, that would otherwise have lain dormant in the code base, waiting for a user to discover them. Let’s now take a look at TypeScript in action.

Below, we see an example which I pulled from TJ Van Toll’s article The Rise of TypeScript. Inside this function, we see both the height, and width parameters are expected to be of type number. The : number before the body of the function specifies the return type, which is also of type number. As a result of this, anything passed into this function that is not a number will cause the compiler to throw an error at compile time.

function calculateArea( height: number, width: number ) : number {
  return height * width;
}
console.log(calculateArea(2,3));
//Will work just fine

console.log(calculateArea("Ten", "Eleven"));
//Argument of type 'string' is not assignable to parameter of type 'number'.

Type declarations help us document our APIs and make our code more maintainable over time.

Installation

The process of compiling TypeScript to JavaScript is extremely easy. First grab the TypeScript package from npm:

npm install -g typescript

Once installed, compiling TypeScript to JavaScript is as easy as running the following command from the command line (TypeScript files are saved using the .ts extension):

tsc <filename.ts>

Now, let’s take a look at how Angular 2 leverages the power of TypeScript to easily create custom components. The code for our first example can be found on the TypeScript branch of our GitHub repo

Creating Our Component in TypeScript

Because TypeScript is a superset of JavaScript, any valid JavaScript will work just fine in .ts files. By using TypeScript, developers are able to extend their JavaScript code to utilize the latest ES6 functionality. In this example, we will be making use of classes.

Below, I have created a component using TypeScript code. The first thing I have done is import Angular using the ES6 import syntax. In this example, we are going to define a component, as well as a view for the component. Once done, we are going to need Angular’s bootstrap function so that Angular runs the code. Inside this code, we will see the @ symbol, which is used to tell Angular about what we are trying to build.

import {Component, View, bootstrap} from 'angular2/angular2';
@Component({
  selector: 'user-name'
})

Because Angular 2 was built on top of TypeScript, the framework recognizes our @Component annotation and knows that we are trying to create a new component. Additionally, it is telling Angular that we want to instantiate a component whenever it sees <user-name></user-name> inside of our HTML.

As mentioned above, a component consists consist of two things:

  • A view
  • Some Logic

Since the component is already defined, we now need to create the view and the logic.

Immediately following our component, we can add some TypeScript code to define our view. Let’s take a look at a continuation of the code above, and see first-hand just how easy Angular makes the process of adding views to custom components:

@View({
  template: '<h1>My name is Tom Greco</h1>'
})
class UserComponent { }

Now, when I add <user-name></user-name> to my index.html file, this template will get injected into the DOM. That being said, the logic portion of our component is empty as our UserComponent class holds no code.

In the example above, I just have an empty class. Now, however, I am going to create a name variable, and then use expressions to render this name variable inside our view:

@View({
  template: '<h1>My name is {{ name }}</h1>'
})
class UserComponent {
  name: 'Tom Greco'
}
bootstrap(UserComponent);

You will also see the bootstrap function I spoke of earlier. Although they share a name, this function is used to start, or bootstrap our Angular application, and does not have anything to do with the Twitter BootStrap framework. If we forget to pass our component into this function, Angular will not know to load our component.

Another thing I want to quickly note is that our application must be viewed using some kind of server in order for it to display correctly. If it is accessed directly, then System.js will not be able to load our main module, which holds our code.

Those using the repository for this example can run node app.js inside of the root directory now. Once this command is run, we can see our component in action by visiting http://localhost:8000. Hopefully this demonstrates how easy Angular makes adding logic to a component!

Migrating Our Component to ES5

For those who want to harness the power of 2.0 with ES5, the Angular 2 team has created a version of the framework that can simply be dropped into a website. This is necessary because ES5 doesn’t have a module system, so we need some kind of self-executing bundle. If you checked out the code for the first example, you will see that I needed to add three different script tags into the application. In this example, all we need to do is add the script below.

<script src="http://code.angularjs.org/2.0.0-alpha.30/angular2.sfx.dev.js"></script>

With the help of this script, developers can use their knowledge of ES5, and not have to worry about sacrificing any of the framework’s functionality. Let’s take a look at how we can build out an Angular component in ES5. The code for this example can be found at on the ES5 branch of our GitHub repo. That said, let’s get started!

In order to recreate the component using ES5 instead of TypeScript, I am going to make use of some different methods. This is essentially the same thing that I did in the example above, however instead of using using the @ symbol, we will chain methods on the ng object. This is shown in the code below:

var UserComponent = ng.Component({
  selector: 'user-name'
})

Now, we can continue to add functionality to our component which will be shown every time our application reads the <user-name> selector.

Let’s make use of the View, and Class methods. Inside of our View method, we simply need to pass in the template string that we used before. Because classes are not supported in ES5, we are going to mimic the use of them in our Class method, by creating a simple constructor function, which will hold our name property.

.View({
  template: '<h1>My name is {{ name }}</h1>'
})
.Class({
  constructor: function(){
    this.name="Tom Greco";
  }
});

We are missing one thing though. In our TypeScript example, we made use of the bootstrap function to jump-start our Angular code. Here’s how we can do the same in ES5:

<script>
  document.addEventListener('DOMContentLoaded', function () {
    angular.bootstrap(UserComponent);
  });
</script>

This should be placed below our custom app code. This will cause Angular to bootstrap our application, and load the component once the page has loaded. Unlike our previous example (which needed a server), this page can be viewed directly in the browser.

As you can see, the Angular team has provided a clear solution for those who wish to build applications in 2.0 using ES5. If this is something that interests you, I highly recommend you checkout the a.js library, which allows developers to build Angular apps in ES5 using a TypeScript-inspired syntax.

Conclusion

Hopefully this has given you an insight into various aspects of Angular that will be arriving in the next version of the framework. If you would like to take this further and build a complete app using Angular 2 and TypeScript (a pinboard in this case), then I recommend checking out this article: Getting Started with Angular 2 using TypeScript.

I’d also love to hear about your experiences with Angular 2. Did you try it out already? Did you build something you’d like to share. Let me know in the comments.

  • http://SalaryNet30.com shannon mcfadden

    Like Antonio responded I am taken by
    surprise that a stay at home mom able to make $5849 in a few weeks on the
    internet. have a peek at this website on my profIle

    -==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=–=-=-=-=-=–=-=-=-=-=-=–=-=-=–=-=-=-=-=-=-=-=-=–=-=-=-=-=–=

    +gffgfggg

  • Lars Jeppesen

    Great article, thanks

  • konstantin.magg

    Hey Tom,
    thx for this clear and detailed comparison between TypeScript and JavaScript.

    If you continue this approach with Angular 2 on ES5, there are some difficulties ahead, e.g. dependecy injection, implementing Angular Base Classes or accessing Angular Core Components, that are not available in the docs yet. Did you already figure out a clean way to configure the ng.router?

    Thx for this informative article anyway.
    Best – Konstantin

  • Syreeta Albin

    Timely commentary – Coincidentally , others a USPS PS 3817 , We filled out a template version here http://goo.gl/xVq9ZH

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.