Learning Angular 2 - Pablo Deeleman - E-Book

Learning Angular 2 E-Book

Pablo Deeleman

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Your quick, no-nonsense guide to building real-world apps with Angular 2

About This Book

  • The first and best overview of Angular 2 on the market—this guide gathers together everything there is to know about Angular 2 and groups it into intuitive sections.
  • This book is your detailed map of every feature and its use cases.
  • The author has done all the hard work of fitting everything Angular 2 means for developers together for you, making this book the quickest way to learn Angular 2 from scratch.

Who This Book Is For

This book is targeted at web developers who want to build the next generation of state-of-the-art mobile and desktop web applications with Angular 2. This book does not require you to have prior exposure to either Angular 1.x or 2, although comprehensive knowledge of JavaScript is assumed. It's great for newcomers to Angular who learn best through clear explanations and definitions of concepts.

What You Will Learn

  • Set up your working environment in order to have all the tools you need to start building Angular 2 components with minimum effort
  • Get up to speed with TypeScript, a powerful typed superset of JavaScript that compiles to plain JavaScript
  • Take full control of how your data is rendered and updated upon data changes
  • Build powerful web applications based on structured component hierarchies that emit and listen to events and data changes throughout the elements tree
  • Explore how to consume external APIs and data services and allow data editing by harnessing the power of web forms made with Angular 2
  • Deliver seamless web navigation experiences with application routing and state handling common features with ease
  • Discover how to bulletproof your applications by introducing smart unit testing techniques and debugging tools

In Detail

Angular 2 was conceived as a complete rewrite in order to fulfill the expectations of modern developers who demand blazing fast performance and responsiveness from their web applications.

This book will help you learn the basics of how to design and build Angular 2 components right from the beginning, providing full coverage of the TypeScript syntax required to follow the examples included. From that point on, we will build upon our first components, interconnect them, and give shape to larger web applications. We will then move to implementing routing in Angular 2, analyzing how to handle application states, and navigating from one component to another in depth. After this, the book features full coverage of web forms and user input validation, later leveraging all of this information to go through the basics of implementing user authentication in Angular 2 and providing a bird's eye view of the different strategies at hand to secure pages and areas of your website. Animating components and DOM elements with Angular 2 is also covered in this book. The final part of this book provides broad insights into how to unit test components and other modules such as services, directives, routes or pipes.

Style and approach

This book covers everything there is to know about getting well-acquainted with Angular without bogging you down. Everything is neatly laid out under clear headings for quick consultation, offering you the information required to understand a concept immediately, with short relevant examples of each feature.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 445

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Angular 2
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Creating Our Very First Component in Angular 2
A fresh start
Web components
Why TypeScript over other syntaxes?
Setting up our workspace
Installing dependencies
Installing TypeScript
Installing TypeScript typings
Hello, Angular 2!
TypeScript classes
Introducing metadata decorators
Compiling TypeScript into browser-friendly JavaScript
The HTML container
Serving the examples of this book
Putting everything together
Enhancing our IDE
Sublime Text 3
Atom
Visual Studio Code
WebStorm
Leveraging Gulp with other IDEs
Diving deeper into Angular 2 components
Improving productivity
Component methods and data updates
Adding interactivity to the component
Improving the data output in the view and polishing the UI
Summary
2. Introducing TypeScript
Understanding the case for TypeScript
The benefits of TypeScript
Introducing TypeScript resources in the wild
The TypeScript official site
The TypeScript Wiki
Types in TypeScript
String
Declaring our variables the ECMAScript 6 way
Number
Boolean
Array
Dynamic typing with the any type
Enum
Void
Type inference
Functions, lambdas, and execution flow
Annotating types in our functions
Function parameters in TypeScript
Optional parameters
Default parameters
Rest parameters
Overloading the function signature
Better function syntax and scope handling with lambdas
Classes, interfaces, and class inheritance
Anatomy of a class – constructors, properties, methods, getters, and setters
Interfaces in TypeScript
Extending classes with class inheritance
Decorators in TypeScript
Class decorators
Extending the class decorator function signature
Property decorators
Method decorators
Parameter decorators
Organizing our applications with modules
Internal modules
External modules
The road ahead
Summary
3. Implementing Properties and Events in Our Components
A better template syntax
Data bindings with input properties
Some extra syntactic sugar when binding expressions
Event binding with output properties
Input and output properties in action
Setting up custom values declaratively
Communicating between components through custom events
Emitting data through custom events
Local references in templates
Alternative syntax for input and output properties
Configuring our template from our component class
Internal and external templates
Encapsulating CSS styling
The styles property
The styleUrls property
Inline style sheets
Managing view encapsulation
Summary
4. Enhancing Our Components with Pipes and Directives
Directives in Angular 2
Core directives
NgIf
NgFor
NgStyle
NgClass
NgSwitch, NgSwitchWhen, and NgSwitchDefault
Manipulating template bindings with Pipes
The uppercase/lowercase pipe
The number, percent, and currency pipes
The number pipe
The percent pipe
The currency pipe
The slice pipe
The date pipe
The JSON pipe
The replace pipe
The i18n pipes
The i18nPlural pipe
The i18nSelect pipe
The async pipe
Putting it all together in the Pomodoro task list
Setting up our main HTML container
Building our task list table with Angular directives
Toggling tasks in our task list
Displaying state changes in our templates
Embedding child components
Building our own custom pipes
Anatomy of a custom pipe
A custom pipe to better format time output
Filtering out data with custom filters
Building our own custom directives
Anatomy of a custom directive
Building a task tooltip custom directive
A word about naming conventions for custom directives and pipes
Summary
5. Building an Application with Angular 2 Components
Introducing the component tree
Common conventions for scalable applications
File and module naming conventions
Ensuring seamless scalability with facades or barrels
How dependency injection works in Angular 2
Injecting dependencies across the component tree
Restricting dependency injection down the component tree
Restricting provider lookup
Overriding providers in the injector hierarchy
Extending injector support to custom entities
Initializing applications with bootstrap()
Switching between development and production modes
Enabling Angular 2's built-in change detection profiler
Introducing the Pomodoro App directory structure
Refactoring our application the Angular 2 way
The shared context
Services in the shared context
Configuring application settings from a central service
Creating a facade module including a custom providers barrel
Creating our components
The timer context
The tasks context
Defining the top root component
Bootstrapping the application
Summary
6. Asynchronous Data Services with Angular 2
Strategies for handling asynchronous information
Observables in a nutshell
Reactive functional programming in Angular 2
The RxJS library
Introducing the HTTP API
When to use the Request and RequestOptionsArgs classes
The Response object
Handling errors when performing Http requests
Injecting the Http class and the HTTP_PROVIDERS modules symbol
A real case study – serving Observable data through HTTP
Adding tasks to our tasks service
Summary
7. Routing in Angular 2
Adding support for the Angular 2 router
Setting up the router service
Building a new component for demonstration purposes
Configuring the RouteConfig decorator with the RouteDefinition instances
The router directives – RouterOutlet and RouterLink
Triggering routes imperatively
CSS hooks for active routes
Handling route parameters
Passing dynamic parameters in our routes
Parsing route parameters with the RouteParams service
Defining child routers
Linking to child routes
The Router lifecycle hooks
The CanActivate hook
The OnActivate Hook
The CanDeactivate and OnDeactivate hooks
The CanReuse and OnReuse hooks
Advanced tips and tricks
Redirecting to other routes
Tweaking the base path
Finetuning our generated URLs with location strategies
Loading components asynchronously with AsyncRoutes
Summary
8. Forms and Authentication Handling in Angular 2
Two-way data binding in Angular 2
The NgModel directive
Binding a type to a form with NgModel
Bypassing the CanDeactivate router hook upon submitting forms
Tracking control interaction and validating input
Tracking changes with local references
Controls, ControlGroups, and the FormBuilder class
Introducing Controls and Validators
Controls in the DOM – the ngControl directive
Grouping controls in the DOM with NgControlGroup
Defining control groups imperatively with ControlGroup
Connecting the DOM and the controller with ngFormModel
A real example – our login component
The login feature context
The login form template
The login component
Applying custom validation to our controls
Watching state changes in our controls
Mocking a client authentication service
Exposing our new service to other components
Blocking unauthorized access
Making the UI reactive to the user authentication status
Running the extra mile on access management
Building our own secure RouterOutlet directive
Summary
9. Animating Components with Angular 2
Creating animations with plain vanilla CSS
Handling animation with CSS class hooks
Class hooks available
Animating components with the AnimationBuilder
The CssAnimationBuilder API
Tracking animation state with the Animation class
Developing custom animation directives
Interacting with our directive from the template
Looking into the future with ngAnimate 2.0
Summary
10. Unit testing in Angular 2
Why do we need tests?
Parts of a unit test in Angular 2
Dependency injection in unit tests
Setting up our test environment
Implementing our test runner
Setting up NPM commands
Angular 2 custom matcher functions
Testing pipes
Testing components
Testing components with dependencies
Overriding component dependencies for refined testing
Testing routes
Testing routes by URL
Testing redirections
Testing services
Testing asynchronous services
Mocking Http responses with MockBackend
Testing directives
The road ahead
Using Jasmine in combination with Karma
Introducing code coverage reports in your test stack
Implementing E2E tests
Summary
Index

Learning Angular 2

Learning Angular 2

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2016

Production reference: 2260516

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-207-4

www.packtpub.com

Credits

Author

Pablo Deeleman

Reviewer

Johannes Weber

Commissioning Editor

Sarah Crofton

Acquisition Editor

Reshma Raman

Content Development Editor

Samantha Gonsalves

Technical Editor

Mohita Vyas

Copy Editors

Roshni Banerjee

Akshata Lobo

Project Coordinator

Sanchita Mandal

Proofreader

Safis Editing

Indexer

Priya Sane

Graphics

Kirk D'Penha

Production Coordinator

Nilesh R. Mohite

Cover Work

Nilesh R. Mohite

About the Author

Pablo Deeleman is a former UX designer and frontend engineer who discovered the Web back in the 90s, when a 14,400 bps modem was the key to an unparalleled world of marvels and a build-your-own-website was the name of the game.

After getting his BA (Hons) degree in marketing and moving through different roles in the advertising arena, he took his chance and evolved into a self-taught, passionate UX designer and frontend developer with a crunch for beautifully crafted CSS layouts and JavaScript thick clients, having produced countless interactive designs and web desktop and mobile applications ever since.

During these years, he has fulfilled his career as both an UX designer and frontend developer by successfully leading Internet projects for a wide range of clients and teams, encompassing European online travel operators, Silicon Valley-based start-ups, international heavy-traffic tube websites, global banking portals, or gambling and mobile gaming companies, just to name a few. At some point along this journey, the rise of Node.js and single-page-application frameworks became a turning point in his career, being currently focused on building JavaScript-driven web experiences.

After having lived and worked in several countries, Pablo Deeleman currently lives in Barcelona, Spain, where he leads the frontend endeavor in the Barcelona studio of Gameloft, the world leader in mobile gaming, and the home of internationally acclaimed games, such as Despicable Me: Minions Rush and Asphalt 8.

When not writing books or taking part in industry events and talks, he spends most of his time fulfilling his other passion: playing piano and guitar.

Acknowledgments

The book you hold in your hands right now is the result of a lot of time, effort, and sacrifice. Someone wisely said once that writing a book about a framework in the alpha stage is like aiming at a moving target, and indeed it is. During the writing, the author and the team involved in this project wound up losing track of how many times we had rewritten everything to conform to the latest incarnation of the framework. In the heat of the battle, it is quite easy to fall under the weight of frustration and seriously consider whether such a project is worth the effort or not. In that sense, this is why I only have words of appreciation for the team at Packt and most particularly for Samantha Gonsalves. Her kind words of support fueled the energy I needed to move this project ahead.

I would also like to specially thank my friend and tech author Jorge Ferrando for his guidance and hints during the production process for this book. His expertise in Angular 2 became priceless when assessing the different courses of action to deliver the best learning experience. A mention is required as well for our other fellow developers Javier Gómez, Alfonso Fernández, Fran Iruela, and Pedro Narciso.

I'd like to also thank the people who have mentored me and accompanied me along this professional journey over these years, with a special mention for the people at Casumo and Gameloft, and most specifically and in no particular order, for Razmus Svenningson, Kim Larsen, Josef Galea, Steve Attard, Iden Azzopardi, Renald Dalli, Matthew Borg, Mark Busuttil, Gerard Giné, Antonio González, Albert Puértolas, Rafael Marfil and the always inspiring Stuart Langridge.

About the Reviewer

Johannes Weber is a passionate developer and adviser in the field of web technologies spotlighted on enterprise JS apps. He works for Mayflower GmbH (Munich, Germany), where he focuses on the migration of SPA and MPA. In his free time, he (co)organizes the AngularJS Munich meetups, AngularCamp and JS-Kongress.de. Johannes cofounded ESnextNews.com, where you get five great ECMAScript.next links every week in your inbox.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

This book is dedicated to my parents Paul and Pepa, and in the loving memory of my brother José Raúl.

You will live forever in our hearts.

Preface

Over the past years, Angular 1.x has became one of the most ubiquitous JavaScript frameworks for building cutting edge web applications, either big or small. At some point, its shortcomings with regard to performance and scalability became too prominent as soon as applications grew in size and complexity. Angular 2 was then conceived as a full rewrite from scratch to fulfill the expectations of modern developers, who demand blazing fast performance and responsiveness in their web applications.

Angular 2 has been designed with modern web standards in mind and allows full flexibility when picking up your language of choice, providing full support for ES6 and TypeScript, but working equally well with today's ES5, Dart, or CoffeeScript. Its built-in dependency injection functionalities let the user build highly scalable and modular applications with an expressive and self-explanatory code, turning maintainability tasks into a breeze, while simplifying test-driven development to the max. However, where Angular 2 stands out is when it shows off its unparalleled level of speed and performance, thanks to its new change detection system that is up to five times faster than its previous incarnation. Cleaner views and an unsurpassed standards-compliant templating syntax compound an endless list of powerful features for building the next generation of web mobile and desktop apps.

Angular 2 is here to stay and will become a game changer in the way modern web applications are envisioned and developed in the years to come. However, and due to its disruptive design and architecture, learning Angular 2 might seem a daunting effort to newcomers.

This is where this book comes in—its goal is to avoid bloating the reader with API references and framework descriptions, but to embrace a hands-on approach, helping the reader learn how to leverage the framework to build stuff that matters right from day one. This is learning by doing right from the start.

This book aims to give developers a complete walkthrough of this new platform and its TypeScript-flavored syntax by building a web project from back to forth, starting from the basic concepts and sample components and iterating on them to build up more complex functionalities in every chapter until we launch a complete, tested, production-ready sample web application by the end of the book.

What this book covers

Chapter 1, Creating Our Very First Component in Angular 2, introduces the reader to web components, which are the building blocks of all Angular 2 applications.

Chapter 2, Introducing TypeScript, instructs the reader about the syntax and particularities of this typed superset of ECMAScript 6, being in fact the syntax of choice of the Angular team for building Angular 2.

Chapter 3, Implementing Properties and Events in Our Components, describes how our components behave like state machines that can change their state by receiving data through their input properties and emit data as events through their output properties.

Chapter 4, Enhancing our Components with Pipes and Directives, gives a complete walkthrough of the framework's built-in pipes used to digest data output in our templates, and also the built-in directives that provide advanced functionality to our component. The reader will also learn how to create custom pipes or directives

Chapter 5, Building an Application with Angular 2 Components, devotes an entire chapter to recap what we have learned so far and orchestrates everything to ensure our Angular 2 projects scale well regardless their size and conform to the community coding and naming conventions.

Chapter 6, Asynchronous Data Services with Angular 2, teaches the reader how to implement and deploy HTTP connections with other data services by means of the Http module, so we can create our own data service clients.

Chapter 7, Routing in Angular 2, introduces the reader to Angular 2's router and its built-in directives, providing a complete walkthrough the different strategies we have to load components from routes and handle the state through the History API.

Chapter 8, Forms and Authentication Handling in Angular 2, illustrates the different strategies we have at our disposal to build web forms with Angular 2, manage two-way data binding on input controls, and create complex forms and validations.

Chapter 9, Animating Components with Angular 2, covers the currently available tools and classes for implementing animations on our components, from pure CSS animations handled with Angular 2 directives to more complex transitions purely managed through JavaScript, thanks to Angular 2 animation builders.

Chapter 10, Unit Testing in Angular 2, will guide the reader through the steps required for implementing a sound testing foundation in our application, and the general patterns for deploying unit tests on components, directives, pipes, routes, and services.

What you need for this book

In order to develop the examples contained in this book, you will primarily need a web browser updated to its latest version. We recommend Google Chrome or Mozilla Firefox, although Angular 2 is meant to be supported in all evergreen browsers.

You will also need terminal software installed on your OS, since many operations are handled through npm commands to the console. In this sense, having Node.js and npm installed on your system will be required to run most of the console commands mentioned in the book. The rest of modules required and their installation procedure will be described as we go.

Last, but not least, you will require a text editor to code your Angular 2 modules, although Chapter 1, Creating Our Very First Component in Angular 2 will provide a thorough walkthrough of all the best IDE alternatives in store nowadays for developing Angular 2 applications.

Who this book is for

This book is targeted at web developers who want to build the next generation of state-of-the-art mobile and desktop web applications with Angular 2. This book does not require you to have prior exposure to either Angular 1.x or 2, although comprehensive knowledge of JavaScript is assumed. It's great for newcomers to Angular who learn best through clear explanations and definition of concepts.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "As a result of this action, we will find a new tsconfig.json file at the root of our project, including the settings required by the TypeScript compiler to transpile the component code into plain ECMAScript 5 JavaScript code readable by current browsers."

A block of code is set as follows:

<body> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <strong class="navbar-brand">My Pomodoro Timer</strong> </div> </div> </nav> <pomodoro-timer></pomodoro-timer> </body>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<body> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <strong class="navbar-brand">My Pomodoro Timer</strong> </div> </div> </nav> <pomodoro-timer></pomodoro-timer> </body>

Any command-line input or output is written as follows:

$ npm install angular2 es6-shim es6-promise reflect-metadata rxjs zone.js --save

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The learn section gives us access to a quick tutorial to get up to speed with the language in no time."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from GitHub at https://github.com/deeleman/learning-angular2.

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

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 versionsLearn how to set up our code environment to work with Angular 2 and TypeScriptEnhance our IDE of choice to provide a better experience coding Angular 2 appsBuild our very first Angular 2 web component and learn how to embed it on a web pageAdd basic interactivity features to our web componentDiscover 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 renderCustom Elements: These templates not only contain traditional HTML elements, but also the custom wrapper items that provide further presentation elements or API functionalitiesShadow DOM: This provides a sandbox to encapsulate the CSS layout rules and JavaScript behaviors of each custom elementHTML 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.

Setting up our workspace

Before jumping into the implementation of our very first and shiny Angular 2 component, we need to bring in all the tools we will require to implement software based on TypeScript, let alone the Angular 2 framework modules themselves.

First and foremost, create a folder and double check that the NPM CLI is available in your system and is properly updated to the latest stable version. Otherwise, please go to https://nodejs.org and install the latest Node.js runtime.

Note

At the time of writing, the Angular 2 framework is in Release Candidate 1 version, so the requirements for building and deploying the examples contained in this book might have changed overnight. The author maintains a code repository at https://github.com/deeleman/learning-angular2, where you can check the most up-to-date version of each example contained in this book. The repository is divided into chapter folders and each folder contains the incremental version of the project as it is at the end of each chapter. Please refer to the code repository should any problem arise upon installing or deploying the examples in the book.

Installing dependencies

Our first requirement will obviously be to install Angular 2 onto our workspace, including its own peer dependencies. The Angular 2 team has made a great effort to ensure the installation is modular enough to allow us to bring only what we need, becoming our projects more or less lean depending on the requirements.

In this sense, Angular 2 does not come in the form of a single installable package, but many. This gives the smart developer the opportunity to pick only those modules that are required for its project, minifying the overall dependencies footprint. Some of these packages, such as common or core, are required regardless the type of project we want to ship. Some others, such as platform-browser-dynamic, are bound to the type of project and target platform addressed. A nonthorough list of the most common packages that you will require in your projects is given here:

@angular/core: This is the most relevant package, encompassing the backbone of Angular and its most common elements, such as directives and components. You will need to rely on this module on a common basis to import the basic elements of Angular 2 into your project.@angular/common: You will seldom need to explicitly import tokens from this module, but it is worth remarking that this package contains the definitions of all the directives, services, and pipes contained by Angular 2, among other relevant classes.@angular/compiler: Same as common, you will rarely import tokens explicitly from this module, although it is the one responsible for compiling the HTML templates and turning them into code that can render the application's UI output.@angular/platform-browser: This module contains classes and functions required for composing and interacting with the DOM in a web browser context. Updating the page title or configuring the touch gestures setup are common actions made possible by this module. This package also contains the functions required to compile templates offline in production environments.@angular/platform-browser-dynamic: We will rely thoroughly on this module during the course of the book, since it will provide us with the bootstrapping function we will require to initialize our applications on development.@angular/http: It is the Angular 2 HTTP client, which we will cover in detail in Chapter 6, Asynchronous Data Services with Angular 2.@angular/router: It is the Angular 2 built-in router still under Beta at the time of this writing.@angular/router-deprecated: A snapshot of the previous incarnation of the Angular 2 built-in router, made available to ensure backward compatibility with existing applications. Chapter 7, Routing in Angular 2, will cover it in detail and explain some of its most remarkable differences with the new router still under development.

At the time of writing, these are all the different third-party libraries that are required as peer dependencies in an Angular 2 project, apart from the Angular 2 modules:

es6-shim: This introduces ECMAScript 6 compatibility polyfills for legacy JavaScript engines (mostly Microsoft Internet Explorer). This dependency is now required because many major browsers still do not provide wide support for ECMAScript 6 features, but hopefully, this will change soon. Some other implementations use the core-js standard library instead. Ultimately, pick the one you like the most as long as it properly polyfills the core ES2015 APIs required by Angular 2.zone.js: This is a polyfill for the Zone specification that is used to handle change detection in Angular 2 applications.reflect-metadata: This brings support for decorators in our Angular 2 classes and metadata reflection in our components. We will see decorators in action later on in this chapter and a broader overview of its different types and implementations in Chapter 2, Introducing TypeScript. Decorators are a core part of Angular 2.rxjs: This library was developed by Microsoft Open Technologies, Inc. According to Microsoft, it is a set of libraries to compose asynchronous and event-based programs using observable collections and Array#extras style composition in JavaScript. In short, RxJS is a library for managing Observables, which allow us to make our applications fully reactive to asynchronous state changes. The Observables spec will be standardized by modern browsers in the future, so we will be able to rule out this dependency by then.

These dependencies may evolve without prior notice so please refer to the GitHub repository for the most up-to-date list of requirements.

Note

You will be probably surprised by the amount of libraries that Angular 2 does need and the fact that these dependencies are not part of the Angular bundle itself. This is because these requisites are not specific to Angular 2, but of a vast majority of modern JavaScript applications nowadays.

With all these dependencies and third-party libraries in mind, you can run the following set of bash commands in your terminal console, once you have created a folder for the project we will cover in this book:

$ mkdir learning-angular2$ cd learning-angular2$ npm init$ npm install @angular/common @angular/core @angular/compiler --save$ npm install @angular/platform-browser @angular/platform-browser-dynamic --save$ npm install @angular/router @angular/router-deprecated --save$ npm install @angular/http --save$ npm install es6-shim reflect-metadata rxjs zone.js --save

Apart from the dependencies enlisted previously, we will also need to install the systemjs universal module loader package in order to support module loading between code units once transpiled into ES5. The systemjs package is not the only option available for managing module loading in Angular 2. In fact, we can swap it for other module loaders, such as WebPack (https://webpack.github.io/), although all the examples provided in this book make use of SystemJS for handling code injection. We will install SystemJS, flagging it as a development dependency by executing the following command:

$ npm install systemjs –save

Last, but not least, we will also install Bootstrap in our application so that we can easily craft a nice UI for the example application we will build incrementally in each chapter. This is not an Angular 2 requirement, but a particular dependency of the project we will carry out throughout this book:

$ npm install bootstrap –save

The installation can throw different alerts and warnings depending on the versions of each peer dependency required by Angular 2 at this moment in time, so in case of issues, I strongly recommend to fetch the latest version of the package.json file available in this book's code repository https://github.com/deeleman/learning-angular2/blob/master/chapter_01/package.json.

Download the file to your directory workspace and run the npm install command. NPM will find and install all the dependencies for you automatically.

Note

Mac OS users, who have not claimed ownership rights on the npm directory located at /usr/local/bin/npm (or /usr/local/npm for those users on OS versions prior to Mac OS El Capitan), might need to execute the npm install command with sudo privileges.

Installing TypeScript

We have now a complete set of Angular 2 sources and their dependencies, plus the Bootstrap module to beautify our project and SystemJS to handle module loading and bundle generation.

However, TypeScript is probably not available on your system yet. Let's install TypeScript and make it globally available on your environment so that we can leverage its convenient CLI to compile our files later on:

$ npm install -g typescript

Great! We're almost done. One last step entails informing TypeScript about how we want to use the compiler within our project. To do so, just execute the following one-time command:

$ tsc --init --experimentalDecorators --emitDecoratorMetadata --target ES5 --module system --moduleResolution node

Basically, we have just initialized a TypeScript project (which is our Angular 2 project itself) with support for experimental decorators (as we mentioned already, these are a new feature in ES7 and TypeScript that Angular 2 uses extensively) and set SystemJS as the default mechanism for importing modules and dependencies between files.

As a result of this action, we will find a new tsconfig.json file at the root of our project, including the settings required by the TypeScript compiler to transpile the component code into plain ECMAScript 5 JavaScript code readable by current browsers.

Note

Please remember that our browsers do not provide support for TypeScript or ECMAScript 6 out of the box, so we will transpile our code to some flavor of JavaScript that is widely supported by our target browsers.

A sneak peek on such file will yield the following:

{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "target": "es5", "module": "system", "moduleResolution": "node", "noImplicitAny": false, "outDir": "built", "rootDir": ".", "sourceMap": false }, "exclude": [ "node_modules" ] }

Simple, right? The set of properties included in our config manifest is self-descriptive enough, but we can highlight three interesting properties. They are as follows:

rootDir: This points to the folder the compiler will use to scan for TypeScript files to compile (currently the base folder in our example).outDir: This defines where the compiled files will be moved unless we define our own output path by means of the --outDir parameter in the command line, the compiler will default to the built folder created at runtime in the same location where the tsconfig.json file lives.sourceMap: This sets the source code mapping preferences to help debugging.

Toggle its value to true if you want source map files to be generated at runtime to back trace the code to its source through the browser's dev tools in case exceptions arise.

Besides these properties, we also can see that we have marked the node_modules folder as excluded, which means that the tsc command will skip that folder and all its contents when transpiling TypeScript files to ES5 throughout the application tree.

Tip

I would encourage you to refer to the TypeScript compiler wiki at https://github.com/Microsoft/TypeScript/wiki/Compiler-Options for a full rundown of options available in the compiler API.

Installing TypeScript typings

Besides the project dependencies, such as Bootstrap and Angular 2's own dependencies, TypeScript does require some additional libraries so we can get the best out of it. Specifically, ES6 extends the JavaScript environment with methods and APIs that need to be described to the TypeScript compiler. Otherwise, it will not recognize them as part of the syntax and will throw errors upon compiling. Whenever we need to instruct the TypeScript compiler about a JavaScript API, either a native one or any other API belonging to a third party library, we will want to use a TypeScript type definition file.

A TypeScript type definition file is basically a file with the d.ts file extension that contains TypeScript interfaces (more on this in Chapter 2, Introducing TypeScript) so we can better perform real-time type checking and prevent compiler errors. Installing type definition files in our projects is not a big deal and just requires having a typings tool installed in our environment. In fact, we need to install a type definition file to ensure that the TypeScript compiler is acquainted with the most up-to-date ES6 API. Good news is that we can install a TypeScript definitions manager tool right from the NPM registry, so we can automate the process of searching, installing and deploying type definition files. Therefore, return to the console and proceed with the following commands:

$ npm install -g typings$ typings install es6-shim --ambient --save

First, we install the typings tool globally and then we leverage the typings CLI to install the es6-shim types definition file into our project, creating the typings.json file that will store the references to the source origin for all type definition files we will install now and later on. A new folder named typings is created and it contains the definition files we require. Without them, basic ES6 features like thenew functional methods of the Array class would not be available.

Before moving forward, we need to tackle one more step regarding the TypeScript typings. When installing type definition files, two façade files are generated by the CLI: typings/main.d.ts and typings/browser.d.ts. However, only one should be exposed to the TypeScript compiler. Otherwise, it will raise an exception after finding duplicated type definitions. Since we are building frontend applications, we will stick to browser.d.ts and exclude main.d.ts and its linked definition files by marking it as excluded at tsconfig.json:

{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "target": "es5", "module": "system", "moduleResolution": "node", "noImplicitAny": false, "outDir": "built", "rootDir": ".", "sourceMap": false }, "exclude": [ "node_modules", "typings/main.d.ts","typings/main"] }

On the other hand, it is actually recommended to exclude the typings folder from your project distribution by including it in your .gitignore file, same as we usually do with the node_modules folder. You only want to include the typings.json manifest when distributing your app and then have all the installation processes handled by npm, so it is very convenient to include the type definition files installation as an action handled by the postinstall script in the package.json file. This way, we can install the npm dependencies and the definition files in one shot. The code is as follows:

"scripts": { "typings": "typings", "postinstall": "typings install" },

When taking this approach, the typings package should be included in the package.json as part of the development dependencies. Thus, reinstall it with the --save-dev flag. Again, please refer to the book code repository at GitHub to fetch the latest version of the package.json file for this chapter.