Switching to Angular 2 - Minko Gechev - E-Book

Switching to Angular 2 E-Book

Minko Gechev

0,0
31,19 €

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

Mehr erfahren.
Beschreibung

Build SEO-friendly, high-performance single-page applications with Angular 2

About This Book

  • Get up to date with the latest changes to Angular 2, including the improvements to directives, change detection, dependency injection, router, and more
  • Understand Angular 2's new component-based architecture
  • Start using TypeScript to supercharge your Angular 2 applications

Who This Book Is For

Do you want to jump in at the deep end of Angular 2? Or perhaps you're interested assessing the changes before moving over? If so, then Switching to Angular 2 is the book for you.

To get the most out of the book, you'll need to be familiar with AngularJS 1.x, and have a good understanding of JavaScript. No knowledge of the changes made to Angular 2 is required follow along.

What You Will Learn

  • Understand the changes made from Angular 1.x with side-by-side code samples to help demystify the Angular 2 learning curve
  • Start working with Angular 2's new method of implementing directives
  • Use TypeScript to write modern, powerful Angular 2 applications
  • Dig in to the change-detection method, and other architectural changes to make sure you know what's going on under the hood of Angular 2.
  • Get to work with the new router in Angular 2
  • Use the new features of Angular 2 including pipes, or the updated features such as forms, services, and the DI module
  • Master server-side rendering in Angular 2 to keep your new applications SEO friendly

In Detail

AngularJS is a JavaScript framework that makes building web applications easier. It is used today in large-scale, high-traffic websites that struggle with under-performance, portability issues, as well as SEO unfriendliness, and complexity at scale.

Angular 2 changes that.

It is the modern framework you need to build performant and robust web applications. “Switching to Angular 2” is the quickest way to get to grips with Angular 2 and will help you transition in to the brave new world of Angular 2.

We'll start with an overview which sets the changes of the framework in context with version 1.x. After that, you will be taken on a TypeScript crash-course so we can take advantage of Angular 2 in its native, statically-typed environment. We'll look at the new change-detection method in detail, how Directives and Components change how you create websites with Angular, the new Angular 2 router, and much more.

By the end of the book, you'll be ready to start building quick and efficient Angular 2 applications that take advantage of all the new features on offer.

Style and approach

Starting with a comparison between Angular versions that is filled with side-by-side code examples to help highlight the changes, each chapter then looks at major changes to the framework as is filled with small examples and sample code to get you started

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 311

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

Switching to Angular 2
Credits
Foreword
About the Author
About the Reviewers
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. Getting Started with Angular 2
The evolution of the Web – time for a new framework
The evolution of ECMAScript
Web Components
WebWorkers
Lessons learned from AngularJS 1.x in the wild
Controllers
Scope
Dependency Injection
Server-side rendering
Applications that scale
Templates
Change detection
Summary
2. The Building Blocks of an Angular 2 Application
A conceptual overview of Angular 2
Changing directives
Getting to know Angular 2 components
Components in action
Components in Angular 2
Pipes
Defining pipes
Change detection
Classical change detection
AngularJS 1.x change detection
In the zone.js
Simplified data flow
Enhancing AngularJS 1.x's change detection
Understanding services
Understanding the new component-based router
Angular 2 route definition syntax
Summary
3. TypeScript Crash Course
Introduction to TypeScript
Compile-time type checking
Better support by text editors and IDEs
There's even more to TypeScript
Using TypeScript
Installing TypeScript with npm
Running our first TypeScript program
TypeScript syntax and features introduced by ES2015 and ES2016
ES2015 arrow functions
Using the ES2015 and ES2016 classes
Defining variables with block scope
Meta-programming with ES2016 decorators
Using configurable decorators
Writing modular code with ES2015
Using the ES2015 module syntax
Taking advantage of the implicit asynchronous behavior
Using aliases
Importing all the module exports
Default exports
ES2015 module loader
ES2015 and ES2016 recap
Taking advantage of static typing
Using explicit type definitions
The type any
Understanding the Primitive types
The Enum types
Understanding the Object types
The Array types
The Function types
Defining classes
Using access modifiers
Defining interfaces
Interface inheritance
Implementing multiple interfaces
Further expressiveness with TypeScript decorators
Writing generic code by using type parameters
Using generic functions
Having multiple type parameters
Writing less verbose code with TypeScript's type inference
Best common type
Contextual type inference
Using ambient type definitions
Using predefined ambient type definitions
Custom ambient type definitions
Defining d.ts files
Summary
4. Getting Started with Angular 2 Components and Directives
The Hello world! application in Angular 2
Setting up our environment
Installing our project repository
Playing with Angular 2 and TypeScript
Digging into the index
Using Angular 2 directives
The ngFor directive
Improved semantics of the directives syntax
Declaring variables inside a template
Using syntax sugar in templates
Defining Angular 2 directives
Setting the directive's inputs
Understanding the directive's constructor
Better encapsulation of directives
Using Angular 2's built-in directives
Introducing the component's view encapsulation
Implementing the component's controllers
Handling user actions
Using a directives' inputs and outputs
Finding out directives' inputs and outputs
Defining the component's inputs and outputs
Passing inputs and consuming the outputs
Event bubbling
Renaming the inputs and outputs of a directive
An alternative syntax to define inputs and outputs
Explaining Angular 2's content projection
Basic content projection in Angular 2
Projecting multiple content chunks
Nesting components
Using ViewChildren and ContentChildren
ViewChild versus ContentChild
Hooking into the component's life cycle
The order of execution
Defining generic views with TemplateRef
Understanding and enhancing the change detection
The order of execution of the change detectors
Change detection strategies
Performance boosting with immutable data and OnPush
Using immutable data structures in Angular
Summary
5. Dependency Injection in Angular 2
Why do I need Dependency Injection?
Dependency Injection in Angular 2
Benefits of DI in Angular 2
Configuring an injector
Dependency resolution with generated metadata
Instantiating an injector
Introducing forward references
Configuring providers
Using existing providers
Defining factories for instantiating services
Child injectors and visibility
Building a hierarchy of injectors
Configuring dependencies
Using the @Self decorator
Skipping the self injector
Having optional dependencies
Using multiproviders
Using DI with components and directives
Introducing the element injectors
Declaring providers for the element injectors
Exploring DI with components
viewProviders versus providers
Using Angular's DI with ES5
Summary
6. Working with the Angular 2 Router and Forms
Developing the "Coders repository" application
Exploring the Angular 2 router
Defining the root component and bootstrapping the application
Using PathLocationStrategy
Configuring routes with @RouteConfig
Using routerLink and router-outlet
Lazy-loading with AsyncRoute
Using Angular 2 forms
Developing template-driven forms
Digging into the template-driven form's markup
Using the built-in form validators
Defining custom control validators
Using select inputs with Angular
Using the NgForm directive
Two-way data-binding with Angular 2
Storing the form data
Listing all the stored developers
Summary
7. Explaining Pipes and Communicating with RESTful Services
Developing model-driven forms in Angular 2
Using composition of control validators
Exploring the HTTP module of Angular
Using Angular's HTTP module
Defining parameterized views
Defining nested routes
Transforming data with pipes
Developing stateless pipes
Using Angular's built-in pipes
Developing stateful pipes
Using stateful pipes
Using Angular's AsyncPipe
Using AsyncPipe with observables
Summary
8. Development Experience and Server-Side Rendering
Running applications in Web Workers
Web Workers and Angular 2
Bootstrapping an application running in Web Worker
Migrating an application to Web Worker
Making an application compatible with Web Workers
Initial load of a single-page application
Initial load of a SPA with server-side rendering
Server-side rendering with Angular 2
Enhancing our development experience
Text editors and IDEs
Hot reloading
Hot reloading in Angular 2
Bootstrapping a project with angular-cli
Using angular-cli
Angular 2 quick starters
Angular 2 seed
Angular 2 Webpack starter
Summary
Index

Switching to Angular 2

Switching to 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: March 2016

Production reference: 2020816

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-620-1

www.packtpub.com

Credits

Author

Minko Gechev

Reviewers

Miško Hevery

Daniel Lamb

Commissioning Editor

Edward Gordon

Acquisition Editor

Kirk D'costa

Content Development Editor

Shweta Pant

Technical Editor

Mohita Vyas

Copy Editor

Akshata Lobo

Project Coordinator

Kinjal Bari

Proofreader

Safis Editing

Indexer

Mariammal Chettiyar

Graphics

Disha Haria

Production Coordinator

Nilesh Mohite

Cover Work

Nilesh Mohite

Foreword

Angular 2 is still Angular, just better. It is still built on the same principles that made you love AngularJS: a quick and powerful solution to building Single Page Applications. In Angular 2, the applications are faster, more visible to SEO and mobile, and are cross-platform ready. So whilst Angular 2 has improved many of the concepts over AngularJS, the philosophy remains true to the original vision.

Switching to Angular 2 is a book that recognizes this. Minko's book successfully helps you to switch your thinking from AngularJS 1.x to Angular 2. From your first interactions with Angular 2 to the last, the core concepts of Angular are maintained throughout. This guide will help you to switch to Angular's new way of doing things. Minko guides you through the changes and new features that have been introduced—components, directives, TypeScript, the new router, and everything else you need to start using Angular 2 for your next project.

As Angular 2 takes up the challenge set by today's changing web development landscape and builds on the legacy of AngularJS, it's incredibly important for the Angular community that there are high quality learning materials such as Minko's book to help Angular developers make that first switch over to the future.

Miško Hevery

Creator of AngularJS and Angular 2

About the Author

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects, including AngularJS 1.x and Angular 2 style guides, angular2-seed, a static code analyzer for Angular 2 projects, aspect.js, angular-aop, and many others. He runs training courses in JavaScript, Angular, and other web technologies.

Minko loves to experiment with theoretical concepts from computer science and apply them in practice. He has spoken about Angular and software development at worldwide conferences and meetups, including ng-conf, ng-vegas, AngularConnect, ITWeekend Kiev, AngularJS-SF, and Angular Berlin.

I want to thank Miško Hevery for his great contributions in software engineering and the technical review of this book. He helped me provide as precise content as possible. To make the code samples for the book easy to run, I used angular2-seed. Core contributor of the project is Ludovic Hénin, who helped make it much more than an Angular 2 starter. I also want to thank to Daniel Lamb, Radoslav Kirov and Tero Parviainen who gave me extremely valuable feedback!

I couldn't complete the book without the dedicated work of the Packt Publishing team.

Finally, I want to thank the team at Google for giving us Angular. They are a constant inspiration.

About the Reviewers

Miško Hevery is the creator of the AngularJS framework. He has a passion for making complex things simple. He currently works at Google, but has previously worked at Adobe, Sun Microsystems, Intel, and Xerox, where he became an expert in building web applications in web-related technologies, such as Java, JavaScript, Flex, and ActionScript.

Daniel Lamb is a senior software development professional and an author who enjoys sharing the knowledge he has gained, specializing in large-scale architecture and frontend web development. His work over the last 16 years has enabled hundreds of millions to engage and interact during billions of visits.

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

Preface

AngularJS is a JavaScript development framework that makes building web applications easier. It is used today in large-scale, high-traffic websites that struggle with underperformance and portability issues, as well as SEO unfriendliness and complexity at scale. Angular 2 changes these.

It is the modern framework you need to build performant and robust web applications. Switching to Angular 2 is the quickest way to get to grips with Angular 2, and it will help you transition into the brave new world of Angular 2.

By the end of the book, you'll be ready to start building quick and efficient Angular 2 applications that take advantage of all the new features on offer.

What this book covers

Chapter 1, Getting started with Angular 2, kicks off our journey into the world of Angular 2. It describes the main reasons behind the design decisions of the framework. We will look into the two main drivers behind the shape of the framework—the current state of the Web and the evolution of frontend development.

Chapter 2, The Building Blocks of an Angular 2 Application, gives an overview of the core concepts introduced by Angular 2. We'll explore how the foundational building blocks for the development of applications provided by AngularJS 1.x differ from the ones in the last major version of the framework.

Chapter 3, TypeScript Crash Course, explains that although Angular 2 is language agnostic, Google's recommendation is to take advantage of the static typing of TypeScript. In this chapter, you'll learn all the essential syntax you need to develop Angular 2 applications in TypeScript!

Chapter 4, Getting Started with Angular 2 Components and Directives, describes the core building blocks for developing the user interface of our applications—directives and components. We will dive into concepts such as view encapsulation, content projection, inputs and outputs, change detection strategies, and more. We'll discuss advanced topics such as template references and speeding up our applications using immutable data.

Chapter 5, Dependency Injection in Angular 2, covers one of the most powerful features in the framework, which was initially introduced by AngularJS 1.x: its dependency injection mechanism. It allows us to write more maintainable, testable, and understandable code. By the end of this chapter, we will know how to define the business logic in services and glue them together with the UI through the DI mechanism. We will also look into some more advanced concepts, such as the injectors hierarchy, configuring providers, and more.

Chapter 6, Working with the Angular 2 Router and Forms, explores the new module for managing forms in the process of developing a real-life application. We will also implement a page that shows the entered through the form data. In the end, we will glue the individual pages together into an application by using the component-based router.

Chapter 7, Explaining Pipes and Communicating with RESTful services, dives into the router and the forms modules in detail. Here, we will explore how we can develop model-driven forms and define parameterized and child routes. We will also explain the HTTP module and see how we can develop pure and impure pipes.

Chapter 8, SEO and Angular 2 in the Real World, explores some advanced topics in the Angular 2 application development, such as running an application in Web Workers and server-side rendering. In the second part of the chapter, we will explore tools that can ease our daily life as developers, such as angular-cli, and angular2-seed, explain the concept of hot reloading, and more.

What you need for this book

All you need to work through most of the examples in this book is a simple text editor or an IDE, Node.js, TypeScript installed, Internet access, and a browser. The examples in the book are tested on Google Chrome 51+ but they should work in all popular browsers supported by Angular 2.

Each chapter introduces the software requirements for running the provided snippets.

Who this book is for

Do you want to jump in at the deep end of Angular 2? Or perhaps you're interested in assessing the changes before moving over? If so, then Switching to Angular 2 is the book for you.

To get the most out of the book, you'll need to have basic understanding of AngularJS 1.x and have a good understanding of JavaScript. No knowledge of the changes made to Angular 2 is required to follow along.

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/mgechev/switching-to-angular2.

You can download the code files by following these steps:

Enter the URL in your browser's address bar.Click on the "Download ZIP" button located in the mid-right part of the screen.

You can also 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 also 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.

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 LinuxChapters 3 and 4 contain further information for the installation process.

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. Getting Started with Angular 2

On September 18, 2014, the first public commit was pushed to the Angular 2 repository. A few weeks later, at ng-europe, Igor and Tobias from the core team gave a short overview of what Angular 2 was expected to be. The vision at that time was far from final; however, one thing was certain—the new version of the framework would be entirely different from AngularJS 1.x.

This announcement brought a lot of questions and controversy. The reasons behind the drastic changes were quite clear—AngularJS 1.x was no longer able to take full advantage of the evolved Web and to completely satisfy the requirements of large-scale JavaScript applications. A new framework would let Angular developers capitalize on developments in web technology in simpler and more direct ways. Yet, people were concerned. One of the biggest nightmares with backward incompatibility for developers is the migration of their current codebases to the new version of the third-party software they use. In Angular's case, after that first announcement, migration looked daunting, even impossible. Later, at ng-conf 2015 and ng-vegas, different migration strategies were introduced. The Angular community came together and shared additional ideas, anticipating the benefits of Angular 2 while preserving the things learned from AngularJS 1.x.

This book is a part of that project. Making the upgrade to Angular 2 is non-trivial, but it is worth it. The main drivers behind the drastic changes in Angular 2 and its lack of backward compatibility are the evolution of the Web, and the lessons learned from the usage of AngularJS 1.x in the wild. Switching to Angular 2 will help you to learn the new framework by understanding how we got here and why Angular's new features make intuitive sense for the modern Web in building high-performance, scalable, single-page applications.

The evolution of the Web – time for a new framework

In the last couple of years, the Web has evolved in big steps. During the implementation of ECMAScript 5, the ECMAScript 6 standard started its development (now known as ECMAScript 2015 or ES2015). ES2015 introduced many changes in the language such as adding built-in language support for modules, block scope variable definition, and a lot of syntactical sugar, such as classes and destructuring.

Meanwhile, Web Componentswere invented. Web Components allow us to define custom HTML elements and attach behavior to them. Since it is hard to extend the existing HTML elements with new ones (such as dialogs, charts, grids, and more) mostly because of the time required for consolidation and standardization of their APIs, a better solution is to allow developers to extend the existing elements the way they want. Web Components provide us with a number of benefits, including better encapsulation, better semantics of the markup we produce, better modularity, and easier communication between developers and designers.

We know that JavaScript is a single-threaded language. Initially, it was developed for simple client-side scripting, but over time, its role has shifted quite a bit. Now with HTML5, we have different APIs that allow audio and video processing, communication with external services through a two-directional communication channel, transferring and processing big chunks of raw data, and more. All these heavy computations in the main thread may create a poor user experience. They may introduce freezing of the user interface when time-consuming computations are being performed. This led to the development of WebWorkers, which allow the execution of the scripts in the background that communicate with the main thread through message passing. This way, multi-threaded programming has been brought to the browser.

Some of these APIs were introduced after the development of AngularJS 1.x had begun; that's why the framework wasn't build with most of them in mind. However, exploiting the APIs gives developers many benefits, such as:

Significant performance improvements.Development of software with better quality characteristics.

Now let's briefly discuss how each of these technologies has been made part of the new Angular core and why.

The evolution of ECMAScript

Nowadays, browser vendors are releasing new features in short iterations, and users receive updates quite often. This helps move the Web forward by allowing developers to take advantage of the bleeding-edge technologies, aiming to improve the Web. ES2015 is already standardized. The implementation of the latest version of the language has already started in the major browsers. Learning the new syntax and taking advantage of it will not only increase our productivity as developers, but also prepare us for the near future when all the browsers will have full support for it. This makes it essential to start using the latest syntax now.

Some projects' requirements may enforce us to support older browsers, which does not support any ES2015 features. In this case, we can directly write ECMAScript 5, which has different syntax but equivalent semantics to ES2015. However, we can take advantage of the process of transpilation. Using a transpiler in our build process allows us to take advantage of the new syntax by writing ES2015 and translating it to a target language that is supported by the browsers.

AngularJS has been around since 2009. Back then, the frontend of most websites was powered by ECMAScript 3, the last main release of ECMAScript prior to ECMAScript 5. This automatically meant that the language used for the framework's implementation was ECMAScript 3. Taking advantage of the new version of the language requires porting of the entirety of AngularJS 1.x to ES2015.

From the beginning, Angular 2 took into account the current state of the Web by bringing the latest syntax in the framework. Although Angular 2 is written with a superset of ES2016 (TypeScript, which we're going to take a look at in a moment), it allows developers to use language of their own preference. We can use ES2015 or, if we prefer not to have any intermediate preprocessing of our code and simplify the build process, even ECMAScript 5.

Web Components

The first public draft of Web Components was published on May 22, 2012, about three years after the release of AngularJS 1.x. As mentioned, the Web Components standard allows us to create custom elements and attach behavior to them. It sounds familiar; we've already used similar concept in the development of the user interface in AngularJS 1.x applications. Web Components sound like an alternative to Angular directives; however, they have more intuitive API, richer functionality, and built-in browser support. They introduced a few other benefits such as better encapsulation, which is very important, for example, in handling CSS-style collisions.

A possible strategy for adding Web Components support in AngularJS 1.x is to change the directives implementation and introduce primitives of the new standard in the DOM compiler. As Angular developers, we know how powerful but also complex the directives API is. It includes a lot of properties such as postLink, preLink, compile, restrict, scope, controller, and many more, and of course, our favorite transclude. Approved as standard, Web Components will be implemented on a much lower level in the browsers, which introduces plenty of benefits such as better performance and native API.

During the implementation of Web Components, a lot of web specialists met the same problems the Angular team did when developing the directives API and came up with similar ideas. Good design decisions behind Web Components include the content element, which deals with the infamous transclusion problem in AngularJS 1.x. Since both the directives API and Web Components solve similar problems in different ways, keeping the directives API on top of Web Components would have been redundant and added unnecessary complexity. That's why the Angular core team decided to start from the beginning by building on top of Web Components and taking full advantage of the new standard. Web Components involves new features, some of them not yet implemented by all browsers. In case our application is run in a browser, which does not support any of these features natively, Angular 2 emulates them. An example for this is the content element polyfilled with the directive, ng-content.

WebWorkers

JavaScript is known for its event loop. Usually JavaScript programs are executed in a single thread and different events are scheduled by being pushed in a queue and processed sequentially, in the order of their arrival. However, this computational strategy is not effective when one of the scheduled events requires a lot of computational time. In such cases the event's handling is going to block the main thread and all other events are not going to be handled until the time consuming computation is complete and passes the execution to the next one in the queue. A simple example of this is a mouse click that triggers an event, in which callback we do some audio processing using the HTML5 audio API. If the processed audio track is big and the algorithm running over it is heavy, this will affect the user's experience by freezing the UI until the execution is complete.

The WebWorker API was introduced in order to prevent such pitfalls. It allows execution of heavy computations inside the context of different thread, which leaves the main thread of execution free, capable of handling user input and rendering the user interface.

How can we take advantage of this in Angular? In order to answer this question, let's think about how things work in AngularJS 1.x. What if we have an enterprise application, which processes a huge amount of data that needs to be rendered on the screen using data binding? For each binding, a new watcher will be added. Once the digest loop is run, it will loop over all the watchers, execute the expressions associated with them, and compare the returned results with the results gained from the previous iteration. We have a few slowdowns here:

The iteration over large number of watchers.Evaluation of expression in given context.Copy of the returned result.Comparison between the current result of the expression's evaluation and the previous one.

All these steps could be quite slow depending on the size of the input. If the digest loop involves heavy computations, why not move it to a WebWorker? Why not run the digest loop inside WebWorker, get the changed bindings, and apply them to the DOM?

There were experiments by the community, which aimed for this result. However, their integration into the framework wasn't trivial. One of the main reasons behind the lack of satisfying results was the coupling of the framework with the DOM. Often, inside the watchers' callbacks, Angular directly manipulates the DOM, which makes it impossible to move the watchers inside WebWorkers since the WebWorkers are invoked in an isolated context, without access to the DOM. In AngularJS 1.x, we may have implicit or explicit dependencies between the different watchers, which require multiple iterations of the digest loop in order to get stable results. Combining the last two points, it is quite hard to achieve practical results in calculating the changes in threads other than the main thread of execution.

Fixing this in AngularJS 1.x introduces a great deal of complexity in the internal implementation. The framework simply was not built with this in mind. Since WebWorkers were introduced before the Angular 2 design process started, the core team took them in mind from the beginning.