Key Takeaways
- Angular 2.0 uses TypeScript, a superset of JavaScript, to optimize performance regarding both page speed and work flow automation. TypeScript allows developers to annotate their JavaScript with type information, which helps catch errors in the code base.
- Angular 2.0 introduces the concept of components, which are reusable bits of code that consist of a view and some logic. Components have replaced directives as the main element of the framework, ensuring code from one section of an application will not interfere with that from another.
- Creating a component in Angular 2.0 with TypeScript involves defining a component class and importing the necessary functions from Angular. The class is then decorated with the @Component decorator and exported for use in other parts of the application.
- Angular 2.0 also supports ES5, the standard version of JavaScript that runs in most browsers. To create a component in Angular 2.0 with ES5, developers can use methods on the ng object to define a component and add functionality. The code can then be run directly in the browser without needing a server.
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.
Frequently Asked Questions about Creating Components in Angular 2 with TypeScript and ES5
How do I create a component in Angular 2 using TypeScript?
Creating a component in Angular 2 using TypeScript involves a few steps. First, you need to import the Component symbol from the Angular core library. Then, you define a component class and decorate it with the @Component decorator. The decorator tells Angular that the class is a component and provides metadata like the selector and template. Finally, you export the component class so it can be used in other parts of your application. Here’s a basic example:import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: '<h1>Hello, Angular!</h1>'
})
export class MyComponent { }
What is the difference between TypeScript and ES5 in Angular 2?
TypeScript and ES5 are both languages you can use to write Angular 2 applications, but they have some key differences. TypeScript is a statically typed superset of JavaScript that adds types and other features to the language. It’s the preferred language for Angular 2 because it makes the code more robust and easier to maintain. ES5, on the other hand, is the standard version of JavaScript that runs in most browsers. It’s possible to write Angular 2 apps in ES5, but you’ll miss out on some of the benefits of TypeScript.
How can I use React components in TypeScript?
To use React components in TypeScript, you need to define the component as a TypeScript class or function. The class or function should extend React.Component or React.FC and define a render method that returns JSX. Here’s an example:import React from 'react';
class MyComponent extends React.Component {
render() {
return <h1>Hello, React!</h1>;
}
}
What is the Tour of Heroes tutorial in Angular?
The Tour of Heroes is a tutorial provided by the Angular team that guides you through the process of building an Angular application from scratch. It covers many of the core concepts in Angular, including components, templates, services, and routing. It’s a great resource for beginners who are learning Angular for the first time.
How do I generate a component using the Angular CLI?
The Angular CLI provides a command to generate a new component: ng generate component
. This command creates a new directory with the component class, template, CSS, and spec files. You can also use the shorter form ng g c
. For example, to generate a component named ‘my-component’, you would run ng g c my-component
.
How can I use a non-TypeScript React component in TypeScript?
To use a non-TypeScript React component in TypeScript, you can use the React.createElement
function. This function takes the component as the first argument and the props as the second argument. Here’s an example:import React from 'react';
import MyComponent from './MyComponent';
const element = React.createElement(MyComponent, { prop: 'value' });
What is the @Component decorator in Angular?
The @Component decorator is a function that takes a configuration object and turns a class into an Angular component. The configuration object can include properties like selector
, which defines the CSS selector that identifies the component, and template
, which defines the HTML that the component renders.
How do I define a component in ES5?
Defining a component in ES5 is a bit more complex than in TypeScript because ES5 doesn’t have classes or decorators. Instead, you can use the angular.module
and angular.component
functions to define a component. Here’s an example:angular.module('myApp', [])
.component('myComponent', {
template: '<h1>Hello, Angular!</h1>'
});
What is the difference between a component and a directive in Angular?
In Angular, a component is a kind of directive that has a template and encapsulates a piece of the user interface. A directive, on the other hand, is a way to add behavior to an existing element or component. For example, you might use a directive to add a click event handler to a button.
How do I use a component in another component in Angular?
To use a component in another component in Angular, you need to include the selector of the component in the template of the parent component. For example, if you have a component with the selector ‘my-component’, you can use it in another component like this:<my-component></my-component>
Thomas Greco is a web developer based out of New York City specializing in full-stack development with the M.E.A.N. stack technologies. Before web development, Thomas worked as a graphic designer, and he continues to utilize his background in design when building web applications. Have a question for Thomas ? You can reach him on Twitter.