27,59 €
Switching to Angular, Third Edition is the go-to book to align and get started with the Angular JavaScript framework. Angular contributor and international speaker Minko Gechev will help you square up and start building Angular apps and provide you an insight to the Google's vision for the framework.
This book is for software developers who want to align with a modern version of Angular that's aligned with Google's vision of Angular version 5 and beyond, using stable APIs that they can depend on today and in the future. Also for anyone assessing changes to Angular and squaring up for a strategic migration to Angular v5, and for AngularJS developers who want to transfer their mindset to modern Angular version 5 and beyond.
Align your work to stable APIs of Angular, version 5 and beyond, with Angular expert Minko Gechev. Angular is the modern Google framework for you to build high-performance, SEO-friendly, and robust web applications. Switching to Angular, Third Edition, shows you how you can align your current and future development with Google's long-term vision for Angular. Gechev shares his expert knowledge and community involvement to give you the clarity you need to confidently switch to Angular and stable APIs.
Minko Gechev helps you get to grips with Angular with an overview of the framework, and understand the long-term building blocks of Google's web framework. Gechev then gives you the lowdown on TypeScript with a crash course, so you can take advantage of Angular in its native, statically typed environment. You'll next move on to see how to use Angular dependency injection, plus how Angular router and forms, and Angular pipes, are designed to work for your projects today and in the future.
You'll be aligned with the vision and techniques of the one Angular, and be ready to start building quick and efficient Angular applications. You'll know how to take advantage of the latest Angular features and the core, stable APIs you can depend on. You'll be ready to confidently plan your future with the Angular framework.
In this book, Minko Gechev continues his direct style of sharing knowledge about Angular that he's developed across more than 40 international presentations to Angular developers. First, Minko explains Google's vision of Angular to you, and then you dive into a clear tutorial to work with Angular that's aligned with Google's vision of Angular.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 322
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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
Second edition: February 2017
Third edition: October 2017
Production reference: 1301017
ISBN 978-1-78862-070-3
www.packtpub.com
Author
Minko Gechev
Copy Editor
Tom Jacob
Acquisition Editor
Dominic Shakeshaft
Indexer
Francy Puthiry
Project Editor
Radhika Atitkar
Graphics
Kirk D'Penha
Content Development Editor
Venugopal Commuri
Production Coordinator
Arvindkumar Gupta
Technical Editor
Anupam Tiwari
Angular is a quick and powerful solution to building Single-Page Applications, where applications are faster, more visible to SEO and mobile devices, and are cross-platform ready. Today the philosophy remains true to the original vision.Switching to Angular, Third Edition, is a book that recognizes this vision. Minko's book successfully helps you to switch your thinking to Angular. From your first interactions with Angular 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 for your next project. As Angular takes up the challenge set by today's changing web development landscape and builds on the legacy of AngularJS, high-quality learning materials, such as Minko's book, are incredibly important for the Angular communityto help Angular developers make that switch over to the future.
Miško Hevery
Creator of AngularJS and Angular
Minko Gechev is a Google Developer Expert for the Angular team and a presenter at over 40 worldwide conferences, including ng-conf, AngularConnect, AngularUP, and many others. Minko is co-author of the official Angular style guide, and has developed codelyzer – a tool for static analysis of Angular applications and best practices, which is part of the Angular CLI, and currently has over a million downloads each month.
Minko is a former member of the Angular Mobile Team where his role involved him with tools for facilitating the process of developing Progressive web applications with Angular easier. Other projects by the author include the AngularJS style guide, which is translated to 13 different languages, aspect.js, Angular Seed, and many others.
Minko Gechev is co-founder and CTO at Rhyme and strongly believes in open source software.
For support files and downloads related to your book, please visit www.PacktPub.com. 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://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788620704.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
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
Downloading the color images of this book
Errata
Piracy
Questions
Switching to the One Angular
Introducing the One Angular
From AngularJS to Angular
The new beginning
Angular and SemVer
Summary
Get Going with Angular
The evolution of the web – time for a new framework
The evolution of ECMAScript
Web components
Web workers
Lessons learned from AngularJS in the wild
Controllers
Scope
Dependency injection
Server-side rendering
Applications that scale
Templates
Change detection
Summary
The Building Blocks of an Angular Application
A conceptual overview of Angular
Changing directives
Getting to know Angular components
Components in action
Components in Angular
Angular modules
Bootstrapping an Angular application
Pipes
Defining pipes
Improving change detection
Classical change detection
Change detection in AngularJS
In zone.js
Simplified data flow
Enhancing AngularJS's change detection
Services
The new router
Angular route definition syntax
Summary
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 syntaxes 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 of the module
Using aliases
Importing all the module exports
Default exports
ES2015 module loader
ES2015 and ES2016 recap
Taking advantage of static typing
Using explicit type declarations
The any type
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 using type parameters
Using generic functions
Having multiple type parameters
Writing less verbose code with the type inference of TypeScript
Best common type
Contextual type inference
Introducing structural typing
Using ambient type definitions
Using predefined ambient type definitions
Custom ambient type definitions
Summary
Getting Started with Angular Components and Directives
The "Hello world!" application in Angular
Setting up our environment
Installing the sample project repository
Using Angular and TypeScript
Using Angular directives
The ngFor directive
Improved semantics of the directives syntax
Declaring variables inside a template
Using syntax sugar in templates
Defining Angular directives
Setting the directive's inputs
Understanding the directive's constructor
Better encapsulation of directives with NgModules
Using NgModules for declaring reusable components
Using the custom element schema
Creating custom Angular components
Introducing the component's view encapsulation
Implementing the component's controllers
Handling user actions
Using inputs and outputs
Determining the inputs and outputs
Defining the inputs and outputs
Passing inputs and consuming the outputs
Event bubbling
Renaming the inputs and outputs
An alternative syntax to define inputs and outputs
Explaining Angular's content projection
Basic content projection in Angular
Projecting multiple content chunks
Nesting components
Using view children and content children
View child versus content child
Hooking into the component's life cycle
Order of execution of the life cycle hooks
Defining generic views with TemplateRef
Understanding and enhancing the change detection
The order of execution of the change detectors
Understanding Angular's change detection strategies
Introducing immutable data structures and OnPush
Using immutable data in Angular
Summary
Dependency Injection in Angular
Why do I need dependency injection?
Dependency injection in Angular
Benefits of using dependency injection
Declaring providers
Using the @Injectable decorator
Introducing forward references
Configuring providers
Using existing providers
Defining factories for instantiating services
Declaring optional dependencies
Understanding multiproviders
Child injectors and visibility
Instantiating an injector
Building a hierarchy of injectors
Using dependency injection with components and directives
Introducing the element injectors
Declaring providers for the element injectors
Exploring dependency injection with components
View providers versus providers
Using the @SkipSelf decorator
Summary
Working with the Angular Router and Forms
Developing the "Coders repository" application
Exploring the Angular router
Using PathLocationStrategy
Configuring routes
Using routerLink and router-outlet
Lazy-loading with loadChildren
Prefetching of the lazy-loaded routes
RouterModule.forRoot versus RouterModule.forChild
Using Angular's forms module
Developing template-driven forms
Digging into the markup of the template-driven form
Using the built-in validators
Defining custom validators
Using select inputs with Angular
Using the NgForm directive
Two-way data binding with Angular
Storing the form data
Listing all the stored data
Summary
Explaining Pipes and Communicating with RESTful Services
Developing model-driven forms in Angular
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
Tooling and Development Experience
Running an application in a web worker
Web workers and Angular
Bootstrapping an application running in a web worker
Migrating an application to web workers
Making an application compatible with web workers
Initial load of a single-page application
Initial load of a single-page application with server-side rendering
Server-side rendering with Angular
Enhancing our development experience
Text editors and IDEs
Angular language service
Bootstrapping a project with angular-cli
Using angular-cli
Angular quick starters
Angular seed
Angular webpack starter
Ahead-of-time compilation in Angular
How code generation works
Introducing the concept of ahead-of-time compilation
Constraints of the ahead-of-time compilation
How to use the ahead-of-time compilation of Angular
Summary
AngularJS is a JavaScript development framework that makes building web applications easier. It is used today in millions of high-traffic web applications. Although, AngularJS served its purpose well over the past years web evolved and now the framework struggles with performance and scalability issues.
In 2016, Google released Angular—a new framework for building scalable, performant application, inspired by AngularJS. This book allows you to align your work to the stable APIs of Angular, version 5 and beyond, with Angular expert Minko Gechev. With Switching to Angular, Third Edition, we will go through a journey that will help us utilize Google's long term vision for Angular in our future development. This books provides a detailed insight and knowledge to give us the clarity we need to confidently switch into the stable APIs of the framework.
By the end of the book, you'll be able to align with Google's vision for Angular version 5 and beyond, with confidence. But primarily, you will learn how to build high-performance, scalable, and SEO-friendly enterprise applications with Angular and TypeScript.
Chapter 1, Switching to the One Angular, makes an introduction of what Angular is. You'll learn that Angular and AngularJS are entirely different frameworks. After that, we'll go through the basics of the structure of the framework—having a core with a minimalistic and immutable API, and building on top of it with different modules in order to provide the best development experience possible. Finally, we'll see how Angular follows semantic versioning, which helps us understand why and when we should expect incompatible API changes in Angular.
Chapter 2, Get Going with Angular, teaches why we should use the latest version of the JavaScript language, why to take advantage of web workers, and how Angular takes advantage of all these powerful technologies. We will observe the current direction of frontend development and the lessons learned in the past few years. The chapter describes why AngularJS's architecture was changed in order to allow the development of SEO-friendly, high-performance, single-page applications.
Chapter 3, The Building Blocks of an Angular Application, gives a quick overview of the main building blocks provided by Angular for the development of SPAs. We'll point out the main differences with the core concepts from AngularJS.
Chapter 4, TypeScript Crash Course, introduces you to the TypeScript language that is used for the implementation of Angular. While exploring the language, we'll look at some of the core features of ES2015 and ES2016. We will explain the ES2015 and ES2016 classes, arrow functions, block scope variable definitions, destructuring, and modules. Since Angular takes advantage of the ES2016 decorators, and more accurately their extension in TypeScript, a section here speaks about them. After this, we'll take a look at how we can take advantage of static typing using explicit type definitions. We'll describe some of the built-in types in TypeScript and how we can define classes in the language by specifying access modifiers for their members. In the end, we'll explain what structural typing is and how TypeScript's type system takes advantage of it.
Chapter 5, Getting Started with Angular Components and Directives, takes us through the core building blocks of an Angular application: directives and components. We'll build a couple of sample components to show us the syntax to be used for the definition of these fundamental building blocks. You'll learn about the life cycle of each directive and the core set of features the given directive and component have. In the next step, we'll see how we can enhance the performance of our application using Angular's change detection strategies and immutable data structures.
Chapter 6, Dependency Injection in Angular, covers the dependency injection (DI) mechanism of Angular. We'll briefly discuss the positives of using DI in our projects by introducing it in the context of the framework. The second step in our journey is how to configure injectors using Angular modules; we'll also explain the injectors hierarchy and the visibility of the registered providers. In order to enforce a better separation of concerns, we'll take a look at how we can inject services carrying the business logic of our application in our directives and components.
Chapter 7, Working with the Angular Router and Forms, explains the basics of routing in Angular. We will take a look at how we can define different routes and implement the components associated with them that are displayed on route change. After that, we'll explain how to develop template-driven forms with built-in and custom validation. Finally, we'll explain how we can use two-way data-binding in Angular.
Chapter 8, Explaining Pipes and Communicating with RESTful Services, helps us take a deep dive into the Angular's forms module by developing a model-driven (reactive) form, combining it with the HTTP module. We'll take a look at some advanced features of the new component-based router and see how we can use and develop custom stateful and stateless pipes.
Chapter 9, Tooling and Development Experience, goes one step further, describing how to use web workers for performance-sensitive applications. Then, we'll learn to build SEO-friendly applications with server-side rendering. After that, we'll take a look at how to bootstrap a project as quickly as possible. Finally, we will learn what Ahead-of-Time (AOT) compilation is and how to use it.
All you need to work through most of the examples in this book is a text editor or an IDE, Node.js, internet access, and a web browser.
Each chapter introduces the software requirements for running the provided snippets.
Developers with AngularJS experience who want to transfer their mindset to the concepts introduced by modern Angular
Software engineers who want to get familiar with the foundational building blocks and modules of Angular
IT professionals interested in assessing changes to Angular and squaring up for a strategic migration to Angular version 5, and beyond, today
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 email [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.
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.
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 emailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your email 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 Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Switching-to-Angular-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/SwitchingtoAngularThirdEdition_ColorImages.pdf.
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 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.
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.
Although the content of this book can be properly digested without any prior AngularJS or Angular experience, you will get most of the book if you are familiar with the basics of AngularJS and you are willing to switch to Angular.
On the internet, often AngularJS and Angular 1are used interchangeably to refer to the AngularJS framework. This misconception leaves AngularJS experts confused about the Angular versioning. Very often, in many community events, I get questions similar to this one:
Here, you can replace X with any number bigger than 2.
The short answer to this question is: no, you don't have to learn a new framework when a new major version is released. In fact, the API deprecations between Angular 2 and Angular 5 can be listed on a few lines.
This confusion was brought mostly by incorrectly referring to AngularJS as Angular 1, which makes developers believe that every new version of Angular will be as different from the old one as Angular is from AngularJS.
Along the remaining sections of this chapter and in Chapter 2, Get Going with Angular, we will explain how Angular differs from AngularJS and why the development of a new framework was required.
Angular is a framework for application development. Its main focus is to provide a solid foundation for the development of the user interface of our applications.
One of the core primitives that the framework provides is its powerful dependency injection mechanism which allows us to easily control the relations between the individual building blocks of our code. Angular's obviously fast change detection provides a way to synchronize the views of our application with the current state of the data model. Being completely transparent to developers, the change detection knows exactly when the model has changed and performs the minimum set of operations in order to reflect the update in the view.
Being able to extend the valid HTML, Angular's templates with custom elements allow us to use a declarative Domain Specific Language (DSL) to express the structure of the user interface of our application and its bindings to the model.
Angular was inspired for all these ideas and many others by its predecessor, AngularJS.
The initial release of AngularJS was on October 20, 2010. The framework nowadays is used in millions of applications around the world. AngularJS got so popular that numerous technologies were inspired by it and even started using it as a foundation.
One such platform for development of mobile applications is Ionic. Over time, the framework was constantly evolving, trying to provide an API as ergonomic and simplistic API as possible while still being powerful and expressive enough to help us develop complex web applications with ease. The API changes between versions were small and usually introduced through a deprecation process. This way, we: as developers: have enough time to go through the transition process and align to the latest changes.
In the meantime, however, the web evolved, and tens of new technologies got created, some of which directly impacted AngularJS itself or gave the framework opportunities for big jumps in terms of performance or ergonomics. Such new APIs were introduced, for example, by the web worker standard, or even new languages such as TypeScript.
This way, although AngularJS was the optimal technology for application development in 2010, it struggled to stay competitive and flawless, given the constantly moving web. This was the birth of the idea for a new framework, inspired by AngularJS, but with more powerful APIs and better performance! Because of the conceptual similarities with AngularJS, Google called this new framework Angular.
The team at Google, willing to take advantage of the most advanced technologies in Angular, decided to start with a solid, statically typed foundation in the face of TypeScript. On top of that, they considered variety of different ways for the improvement of Angular's performance in order to help developers deliver lightning fast experience to the users of our applications.
Given the learned lesson from AngularJS about the constantly evolving browser APIs, the Angular team developed the framework with a small core and a lot of different libraries surrounding it, providing extra features. This way, the framework's foundational APIs will be able to stay as immutable as possible and the entire infrastructure surrounding Angular's core will evolve following the well-defined release process of semantic versioning. You can see some of the modules developed around Angular core in the following figure:
We'll describe some of these modules in the upcoming chapters.
Before going any further, let's have an overview of what semantic versioning actually means.
AngularJS was rewritten from scratch and replaced with its successor, Angular 2. A lot of us were bothered by this big step, which didn't allow us to have a smooth transition between these two versions of the framework. Right after Angular 2 was stable, Google announced that they wanted to follow the so called Semantic Versioning Specification (also known as SemVer).
SemVer defines the version of a given software project as the tripleX.Y.Z, where Z is called patch version, Y is called minor version, and X is called major version. A change in the patch version means that there are no intended breaking changes impacting the public API surface between two versions of the same project, but only bug fixes. The minor version of a project will be incremented when new functionality is introduced, and there are no breaking changes. Finally, the major version will be increased when incompatible changes are introduced in the API.
This means that between versions 2.3.1 and 2.10.4, there are no introduced breaking changes, but only a few added features and bug fixes. However, if we have version 2.10.4 and we want to change any of the already existing public APIs in a backward-incompatible manner (for instance, changing the order of the parameters that a method accepts), we need to increment the major version and reset the patch and minor versions; so we will get version 3.0.0.
The Angular team also follows a strict, predictable schedule. According to it, a new patch version needs to be introduced every week; there should be three monthly minor releases after each major release, and finally, one major release every 6 months. This means that by the end of 2018, there will be Angular 7. However, this doesn't mean that every 6 months we'll have to go through the same migration path like we did between AngularJS and Angular 2. Not every major release will introduce breaking changes that are going to impact our projects. For instance, support for a newer version of TypeScript or change of the last optional argument of a method will be considered as a breaking change. We can think of these breaking changes in a way similar to what happened between AngularJS 1.2 and AngularJS 1.3.
Now that we've introduced Angular's semantic versioning and conventions for referring to the different versions of the framework, we can officially start our journey!
In this chapter, we made an introduction of what Angular is. We explained that Angular and AngularJS are entirely different frameworks.
After that, we went through the basics of the structure of the framework: having a core with a minimalistic, immutable API and building on top of it with different modules in order to provide the best development experience possible.
Finally, we explained how Angular follows semantic versioning, which helps us understand why and when we should expect incompatible API changes in Angular.
In the next chapter, we'll focus on why AngularJS couldn't keep up with the constant evolution of the web, how Angular took advantage of the new, powerful browser API, and how it makes the development of large scale applications easier.
On September 18, 2014, Google pushed the first public commit to the repository that now contains Angular. A few weeks later, at ng-europe, Igor, and Tobias, from the core team, gave a short overview of what were the expected features of the new framework. The vision at that time was far from final; however, one thing was certain: Angular would be an entirely different framework compared to AngularJS.
This announcement brought a lot of questions and controversies. The reasons behind the drastic changes were quite clear: AngularJS was no longer able to take full advantage of the evolved web and the requirements of large-scale JavaScript applications needed to be completely satisfied. A new framework would let Angular developers capitalize on developments in web technology in simpler, more performant, and productive ways. Yet, people were concerned. One of the biggest nightmares with backward incompatibility for developers is the migration of their current code bases 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 2015, different migration strategies were introduced. The Angular community came together and shared additional ideas, anticipating the benefits of the new version of the framework, while preserving the things learned from AngularJS.
This book is a part of that project. Making the upgrade to Angular is now smooth and 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 in the wild. This book will help you learn the new framework by making you understand 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.
Some of the topics that we will discuss in this chapter are as follows:
Using TypeScript and understanding how it extends JavaScript
Building the user interface of Angular applications with a component-based architecture
Using Angular's dependency injection mechanism and delegating the business logic to services
Exploring Angular's router and forms module in depth
Looking at the Ahead-of-Time compilation for building lightning fast applications
In the past 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 JavaScript, 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 components were invented. Web components allow us to define custom HTML elements and attach behavior to them. Since it is hard to extend the existing set of HTML elements with new ones (such as dialogs, charts, and grids), 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 in 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.
As we know, 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 web workers, which allow the execution of the scripts in the background that communicate with the main thread through message passing. This way, multithreaded programming was brought to the browser.
Some of these APIs were introduced after the development of AngularJS had begun; that's why the framework wasn't built with most of them in mind. Taking advantage of the APIs gives developers many benefits, such as the following:
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 Angular core and why.
Nowadays, browser vendors are releasing new features in short iterations, and users receive updates quite often. This helps developers take advantage of bleeding-edge web technologies. 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 will also prepare us for the near future when all browsers will have full support for it. This makes it essential to start using the latest syntax now.
The requirements of some projects may enforce us to support older browsers, which do not support any ES2015 features. In this case, we can directly write ECMAScript 5, which has a different syntax, but has semantics equivalent to ES2015. On the other hand, a better approach will be to 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.
Angular has been around since 2009. Back then, the frontend of most websites was powered by ECMAScript 3—the last main release of ECMAScript before ECMAScript 5. This automatically meant that the language used for the implementation of the framework was ECMAScript 3. Taking advantage of the new version of the language requires porting of the entirety of AngularJS to ES2015.
From the beginning, Angular took into account the current state of the web by bringing the latest syntax in the framework. Angular is written with a superset of ES2016, called TypeScript, which we'll take a look at in Chapter 4, TypeScript Crash Course. The type annotations allow us to take additional performance boost because they open the door for a process called ahead-of-time (AOT) compilation, which as part of the build process, generates efficient code for change detection, rendering, and dependency injection. You can find more about AOT compilation in Chapter 9,
