Chapter 1. Creating Our Very First Component in Angular 2

Unless you were lost in space for the past couple of years, chances are you are well aware of the momentum that modern JavaScript web frameworks and libraries have got in the frontend arena nowadays. We have even reached a stage where a new framework is born every day, forcing frontend developers to assess carefully whether this new cutting-edge code toolkit adds enough value to justify the time and effort required to face its learning curve and put it to good use in our next project.

Eventually, a handful of names ended up gaining more relevance than the rest. We are obviously referring to client-side frameworks that will probably sound pretty familiar to you already: Backbone, Ember, Knockout, Angular 1, and so on.

As the battle for supremacy in the JavaScript world carried on, new frameworks such as React or Aurelia entered the game, favoring web components and harnessing the power of Shadow DOM as the cornerstone of its architecture. Applications built this way proved to be more modular, scalable, and maintainable, let alone their unparalleled level of performance.

Angular 1 had come a long way already since its inception and its shortcomings had become too prominent to be overlooked any longer. It was time for something better and a simple revamp of codebase did not suffice. A more ambitious approach was required and Angular 2 was developed—a new framework engineered from scratch, which fully embraces the newest trends in the industry. It has web components at the heart of its design and it harnesses the power of Shadow DOM to maximize the responsiveness of our web entities against state changes. On top of that, Angular 2 offers a state-of-the-art change detection system baked in to each component, which is responsible for propagating bindings throughout the tree of components that comprise our applications.

The defining traits of Angular 2 go beyond the concept of just being a mere web components framework, since its features encompass pretty much everything you need in a modern web application: component interoperability, universal support for multiple platforms and devices, a top-notch dependency injection machinery, a flexible but advanced router mechanism with support for decoupling and componentization of route definitions, advanced HTTP messaging, and animation or internationalization, just to name a few.

In this chapter, we will:

  • Learn why Angular 2 is so unique in comparison to its previous versions
  • Learn how to set up our code environment to work with Angular 2 and TypeScript
  • Enhance our IDE of choice to provide a better experience coding Angular 2 apps
  • Build our very first Angular 2 web component and learn how to embed it on a web page
  • Add basic interactivity features to our web component
  • Discover some basic helpers to better format the data output

A fresh start

As mentioned before, Angular 2 represents a full rewrite of the Angular 1.x framework, introducing a brand new application architecture completely built from scratch in TypeScript, a strict superset of JavaScript that adds optional static typing and support for interfaces and decorators.

In a nutshell, Angular 2 applications are based on an architecture design that comprises trees of web components interconnected between them by their own particular I/O interface. Each component takes advantage under the covers of a completely revamped dependency injection mechanism. To be fair, this is a simplistic description of what Angular 2 really is. However, the simplest project ever made in Angular is cut out by these definition traits. We will focus on learning how to build interoperable components and manage dependency injection in the next chapters, before moving on to routing, web forms, or HTTP communication. This also explains why we will not make explicit references to Angular 1.x throughout the book. Obviously, it makes no sense to waste time and pages referring to something that will not provide any useful insights on the topic, besides the fact we assume that you might not know about Angular 1.x, so such knowledge does not have any value here.

Web components

Web components is a concept that encompasses four technologies designed to be used together to build feature elements with a higher level of visual expressivity and reusability, thereby leading to a more modular, consistent, and maintainable web. These four technologies are as follows:

  • Templates: These are pieces of HTML that structure the content we aim to render
  • Custom Elements: These templates not only contain traditional HTML elements, but also the custom wrapper items that provide further presentation elements or API functionalities
  • Shadow DOM: This provides a sandbox to encapsulate the CSS layout rules and JavaScript behaviors of each custom element
  • HTML Imports: HTML is no longer constrained to host HTML elements, but to other HTML documents as well

In theory, an Angular 2 component is indeed a custom element that contains a template to host the HTML structure of its layout, the latter being governed by a scoped CSS style sheet encapsulated within a Shadow DOM container. Let's try to rephrase this in plain English. Think of the range input control type in HTML5. It is a handy way to give our users a convenient input control for entering a value ranging between two predefined boundaries. If you have not used it before, insert the following piece of markup in a blank HTML template and load it in your browser:

<input id="mySlider" type="range" min="0" max="100" step="10">

You will see a nice input control featuring a horizontal slider in your browser. Inspecting such control with the browser developer tools will unveil a concealed set of HTML tags that were not present at the time you edited your HTML template. There you have an example of Shadow DOM in action, with an actual HTML template governed by its own encapsulated CSS with advanced dragging functionality. You will probably agree that it would be cool to do that yourself. Well, good news is that Angular 2 gives you the toolset required for delivering this very same functionality, so we can build our own custom elements (input controls, personalized tags, and self-contained widgets) featuring the inner HTML markup of our choice and a very own stylesheet that does not affect (nor is impacted) by the CSS of the page hosting our component.

Why TypeScript over other syntaxes?

Angular 2 applications can be coded in a wide variety of languages and syntaxes: ECMAScript 5, Dart, ECMAScript 6, TypeScript, or ECMAScript 7.

TypeScript is a typed superset of ECMAScript 6 (also known as ECMAScript 2015) that compiles to plain JavaScript and is widely supported by modern OSes. It features a sound object-oriented design and supports annotations, decorators, and type checking.

The reason why we picked (and obviously recommend) TypeScript as the syntax of choice for instructing how to develop Angular 2 applications in this book is based on the fact that Angular 2 itself is written in this language. Being proficient in TypeScript will give the developer an enormous advantage when it comes to understanding the guts of the framework.

On the other hand, it is worth remarking that TypeScript's support for annotations and type introspection turns out to be paramount when it comes to managing dependency injection and type binding between components with a minimum code footprint, as we will see further down the line in this book.

Ultimately, you can carry out your Angular 2 projects in plain ECMAScript 6 syntax if that is your preference. Even the examples provided in the book can be easily ported to ES6 by removing type annotations and interfaces, or replacing the way dependency injection is handled in TypeScript with the most verbose ES6 way.

Note

For the sake of brevity, we will only cover examples written in TypeScript and actually recommend its use because of its higher expressivity thanks to type annotations, and its neat way of approaching dependency injection based on type introspection out of such type annotations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset