Angular 2 By Example - Chandermani Arora - E-Book

Angular 2 By Example E-Book

Chandermani Arora

0,0
38,39 €

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

Mehr erfahren.
Beschreibung

Discover everything you need to know to build your own Angular 2 applications the hands-on way

About This Book

  • Master the Angular way to structure, build, deploy, and test your code
  • Understand Angular 2's new component-based architecture
  • Build a game and workout runner apps on the Angular platform

Who This Book Is For

This book is for JavaScript developers who are new to Angular 2, or are familiar with the basics but want to take things a step further. If you are motivated to learn by doing things actively, this book is for you.

What You Will Learn

  • Design, develop, deploy, and test the apps you build
  • Work your way through every aspect of app development using Angular2
  • Understand the inner workings of Angular's view templating and data-binding capabilities
  • Work on HTML forms and learn the Angular way to bind, validate, and format data
  • Create component, structural, and attribute directives to extend standard HTML behavior
  • Integrate with the server backend and find out about data retrieval and persistence using Angular
  • Gain practical insight into the challenges of building apps using Angular as well as their solutions

In Detail

Angular 2 will help you build faster, more efficient, and more flexible cross-platform applications. Angular 2 is known for taking the pain out of JavaScript development, and enabling more organized, readable, and testable code.

This book builds three apps with varying degrees of complexity. It starts with a simple ҇uess the Number' game, which serves as a platform to launch you into the world of Angular. Next, you will learn to construct a popular ѷ-Minute Workout' app, covering the building blocks of Angular. The final app, Ґersonal Trainer' morphs the existing ѷ-Minute Workout' into a full-fledged personal workout builder and runner, covering advanced directive building, which is the most fundamental and powerful feature of Angular.

In addition to this, you will learn about testability and the framework constructs Angular provides to effectively test your app. The book concludes by providing you with practical advice and useful tips that will come in handy as you build more and more apps with Angular.

Style and approach

This project-based book will get you building fun projects to see how Angular works in the wild. The book focuses more on doing things rather than just reading the theory. The chapters are structured to introduce the concept, then implement it, and finally explain why it worked.

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 627

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

Angular 2 By Example
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
Readers coming from the previous version
Why a new version of Angular?
Angular 2 design
Why use TypeScript?
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
1. Getting Started
Angular basics
The component pattern
Using the component pattern in web applications
Why weren't components used before in Angular?
What's new that enables Angular to use this pattern?
Web Components
Angular and Web Components
Language support in Angular
ES2015
TypeScript
Putting it all together
Angular modules
The basic steps to building Angular applications
The customary Hello Angular app - Guess the Number!
Setting up a development server
Building Guess the Number!
Designing our first component
The host file
An HTML page
Script tags
Custom elements
The component file
The import statement
Decorators
Defining the class
The module file
Bootstrapping
We're up-and-running!
Digging deeper
Interpolation
Tracking changes in the number of tries
Expressions
The safe navigation operator
Data binding
Property binding
Event binding
Structural directives
Revisiting our app
Looking at how our code handles updates
Maintaining the state
Component as the container for the state
Change detection
Initializing the app
Loading the modules needed by our application
Bootstrapping our app
Tools
Resources
Summary
2. Building Our First App - 7 Minute Workout
What is 7 Minute Workout?
Downloading the code base
Setting up the build
The build internals
Code transpiling
Organizing code
The 7 Minute Workout model
App bootstrapping
App loading with SystemJS
Our first component - WorkoutRunnerComponent
Component life cycle hooks
Building the 7 Minute Workout view
The Angular 2 binding infrastructure
Interpolations
Property binding
Property versus attribute
Property binding continued...
Quick expression evaluation
Side-effect-free binding expressions
Angular directives
Target selection for binding
Attribute binding
Style and class binding
Attribute directives
Styling HTML with ngClass and ngStyle
Exploring Angular modules
Comprehending Angular modules
Adding a new module to 7 Minute Workout
Learning more about an exercise
Adding descriptions and video panels
Providing component inputs
Structural directives
The ever-so-useful NgFor
NgFor performance
Angular 2 security
Trusting safe content
Formatting exercise steps with innerHTML binding
Displaying the remaining workout duration using pipes
Angular pipes
Implementing a custom pipe - SecondsToTimePipe
Adding the next exercise indicator using ngIf
Pausing an exercise
The Angular event binding infrastructure
Event bubbling
Event binding an $event object
Two-way binding with ngModel
Summary
3. More Angular 2 – SPA, Routing, and Data Flows in Depth
Exploring Single Page Application capabilities
The Angular SPA infrastructure
Angular routing
Angular router
Routing setup
Pushstate API and server-side url-rewrites
Adding start and finish pages
Route configuration
Rendering component views with router-outlet
Route navigation
Link parameter array
Using the router service for component navigation
Using the ActivatedRoute service to access route params
Angular dependency injection
Dependency injection 101
Exploring dependency injection in Angular
Tracking workout history
Building the WorkoutHistoryTracker service
Integrating with WorkoutRunnerComponent
Registering dependencies
Angular providers
Value providers
Factory providers
Injecting dependencies
Constructor injection
Explicit injection using injector
Dependency tokens
String token
Integrating with WorkoutRunnerComponent - continued
Adding the workout history page
Sorting and filtering history data using pipes
The orderBy pipe
The search pipe
Pipe gotcha with arrays
Angular change detection overview
Hierarchical injectors
Registering component level dependencies
Angular DI dependency walk
Dependency injection with @Injectable
Tracking route changes using the router service
Fixing the video playback experience
Using thumbnails for video
Using the angular2-modal dialog library
Creating custom dialogs with angular2-modal
Cross-component communication using Angular events
Tracking exercise progress with audio
Building Angular directives to wrap HTML audio
Creating WorkoutAudioComponent for audio support
Understanding template reference variables
Template variable assignment
Using the @ViewChild decorator
The @ViewChildren decorator
Integrating WorkoutAudioComponent
Exposing WorkoutRunnerComponent events
The @Output decorator
Eventing with EventEmitter
Raising events from WorkoutRunnerComponent
Component communication patterns
Injecting a parent component into a child component
Using component lifecycle events
Sibling component interaction using events and template variables
Summary
4. Personal Trainer
The Personal Trainer app - the problem scope
Personal Trainer requirements
The Personal Trainer model
Sharing the workout model
The model as a service
The Personal Trainer layout
Personal Trainer navigation with routes
Getting started
Introducing child routes to Workout Builder
Adding the child routing component
Updating the WorkoutBuilder component
Updating the Workout Builder module
Updating app.routes
Putting it all together
Lazy loading of routes
Integrating sub- and side-level navigation
Sub-level navigation
Side navigation
Implementing workout and exercise lists
WorkoutService as a workout and exercise repository
Workout and exercise list components
Workout and exercise list views
Workouts list views
Exercises list views
Building a workout
Finishing left nav
Adding WorkoutBuilderService
Adding exercises using ExerciseNav
Implementing the Workout component
Route parameters
Route guards
Implementing the CanActivate route guard
Implementing the Workout component continued...
Implementing the Workout template
Angular forms
Template-driven and model-driven forms
Template-driven forms
Getting started
Using NgForm
ngModel
Using ngModel with input and textarea
Using ngModel with select
Angular validation
ngModel
The Angular model state
Angular CSS classes
Workout validation
Displaying appropriate validation messages
Adding more validation
Managing multiple validation messages
Custom validation messages for an exercise
Saving the workout
More on NgForm
Fixing the saving of forms and validation messages
Model-driven forms
Getting started with model-driven forms
Using the FormBuilder API
Adding the form model to our HTML view
Adding form controls to our form inputs
Adding validation
Adding dynamic form controls
Saving the form
Custom validators
Integrating a custom validator into our forms
Summary
5. Supporting Server Data Persistence
Angular and server interactions
Setting up the persistence store
Seeding the database
The basics of the HTTP module
Personal Trainer and server integration
Loading exercise and workout data
Loading exercise and workout lists from a server
Adding the HTTP module and RxJS to our project
Updating workout-service to use the HTTP module and RxJS
Modifying getWorkouts() to use the HTTP module
Updating the workout/exercise list pages
Mapping server data to application models
Loading exercise and workout data from the server
Fixing the builder services
Fixing the Workout and Exercise components
Updating the router guards
Performing CRUD on exercises/workouts
Creating a new workout
Updating a workout
Deleting a workout
Fixing the upstream code
Using promises for HTTP requests
The async pipe
Cross-domain access and Angular
Using JSONP to make cross-domain requests
Cross-origin resource sharing
Handling workouts not found
Fixing the 7 Minute Workout app
Summary
6. Angular 2 Directives in Depth
Classifying directives
Components
Attribute directives
Structural directives
Building a remote validator directive
Validating workout names using async validator
Building a busy indicator directive
Injecting optional dependencies with the @Optional decorator
Implementation 1 - using renderer
Angular renderer, the translation layer
Host binding in directives
Property binding using @HostBinding
Attribute binding
Event binding
Implementation 2 - BusyIndicatorDirective with host bindings
Directive injection
Injecting directives defined on the same element
Injecting directive dependency from the parent
Injecting a child directive (or directives)
Injecting descendant directive(s)
Building an Ajax button component
Transcluding external components/elements into a component
Content children and view children
Injecting view children using @ViewChild and @ViewChildren
Tracking injected dependencies with QueryList
Injecting content children using @ContentChild and @ContentChildren
Dependency injection using viewProvider
Understanding structural directives
TemplateRef
ViewContainerRef
Component styling and view encapsulation
Overview of Shadow DOM
Shadow DOM and Angular components
Summary
7. Testing Personal Trainer
The need for automation
Testing in Angular
Types of testing
Testing - who does it and when?
The Angular testing ecosystem
Getting started with unit testing
Setting up Karma for unit testing
The Karma configuration files
The Karma test shim file
Organization and naming of our test files
Unit-testing Angular applications
Unit-testing pipes
Running our test files
Unit-testing components
Angular testing utilities
Managing dependencies in our tests
Unit-testing WorkoutRunnerComponent
Setting up component dependencies
Mocking dependencies - workout history tracker
Mocking dependencies - workout service
Mocking dependencies - router
Configuring our test using TestBed
Starting unit testing
Debugging unit tests in Karma
Unit-testing WorkoutRunner continued...
Using Jasmine spies to verify method invocations
Using Jasmine spies to verify dependencies
Testing event emitters
Testing interval and timeout implementations
Testing workout pause and resume
Unit-testing services
Mocking HTTP request/response with MockBackend
Unit-testing directives
The TestBed class
Testing remote validator
Getting started with E2E testing
Introducting Protractor
Setting up Protractor for E2E testing
TypeScript configuration
Writing E2E tests for the app
Executing our E2E tests
Setting up backend data for E2E testing
More E2E tests
Testing WorkoutRunner
Using page objects to manage E2E testing
Summary
8. Some Practical Scenarios
Building a new app
Seed projects
Seed and scaffolding tools
Yeoman
angular-cli
Angular 2 performance
Byte size
Initial load time and memory utilization
The Angular rendering engine
Server-side rendering
Offloading work to a web worker
Performant mobile experience
Change detection improvements
Change detection
Change detection setup
When does change detection kick in?
How does change detection work?
Change detection performance
Using immutable data structures
Using Observables
Manual change detection
Handling authentication and authorization
Cookie-based authentication
Token-based authentication
Handling authorization
Adding authorization support
Sharing user authentication context
Restricting routes
Conditionally rendering content based on roles
Migrating Angular 1 apps
Should I migrate?
Advantages of Angular 2
Developing Angular 1 apps today for easy migration
One component per file
Avoiding inline anonymous functions
Avoiding $scope!
Using controller as (controller aliasing) syntax everywhere
Avoiding ng-controller
Building using the Angular 1.5+ component API
What to migrate?
Preparing for Angular 2 migration
Identifying third-party dependencies
jQuery libraries
Angular 1 libraries
Choice of language
Migrating Angular 1's Personal Trainer
Setting up Angular 1's Personal Trainer locally
Identifying dependencies
Setting up the module loader
Enabling TypeScript
Adding Angular 2
Bootstrapping the hybrid app
Injecting Angular 2 components into Angular 1 views
Migrating our first view to Angular 2 component
Injecting Angular 1 dependencies into Angular 2
Registering Angular 2 components as directives
Rules of engagement
Angular 1 directives and Angular 2 components
Resource sharing and dependency injection
Sharing an Angular 1 service
Sharing an Angular 2 service
Change detection
Migrating the start and finish pages
Angular 1 directive upgrade
Replacing angular-translate with ng2-translate
Using a bootstrap-ready callback for initialization
Integrating the start and finish pages
Getting rid of angular-translate
Replacing the ui-bootstrap library
Learnings
Summary

Angular 2 By Example

Angular 2 By Example

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 authors, 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 2015

Second edition: November 2016

Production reference: 1281016  

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-719-2

www.packtpub.com

Credits

Authors

Chandermani Arora

Kevin Hennessy

Copy Editor

Safis Editing

Reviewer

Josh Kurz

Project Coordinator

Devanshi Doshi

Commissioning Editor

Sarah Crofton

Proofreader

Safis Editing

Acquisition Editor

Kirk D'Costa

Indexer

Mariammal Chettiyar

Content Development Editor

Samantha Gonsalves

Graphics

Kirk D'Penha 

Technical Editor

Madhunikita Sunil Chindarkar

Production Coordinator

Shantanu N. Zagade

About the Authors

Chandermani Arora is a software craftsman, with a passion for technology and expertise on the web stack.

With more than a decade of experience under his belt, he has architected, designed, and developed solutions of all shapes and sizes on the Microsoft platform.

He has been building apps on Angular 1 from its early days. Such is his love for the framework that every engagement that he is a part of has an Angular footprint.

Being an early adopter of the Angular 2 framework, he tries to support the platform in every possible way – be it writing blog posts on various Angular topics or helping his fellow developers on StackOverflow, where he is often seen answering questions on the Angular2 channel.

An ex-MSFT, he now works for Technovert where he leads a bunch of awesome developers who build cloud-scale web applications using Angular and other new age frameworks.

He is also the author for the first edition of this book, AngularJS by Example.

Writing this book has just been a surreal experience, and I would like to thank my Technovert family who have supported me in all possible ways, be it helping me with the sample apps, reviewing the content, or offloading some of my professional commitment to make sure I get enough time for book writing. And finally I want to express my gratitude towards my family. I know your blessings are always there with me.

Kevin Hennessy is a Senior Software Engineer with Applied Information Sciences. He has 18 years of experience as a developer, team lead, and solutions architect, working on web-based projects, primarily using the Microsoft technology stack. Over the last several years, he has presented and written about single-page applications and JavaScript frameworks, including Knockout, Meteor, and Angular 2. Most recently, he spoke about Angular 2 at the All Things Open Conference. His corporate blog is http://blog.appliedis.com/?s=Kevin+Hennessy.

I would like to acknowledge my wife, Mary Gene Hennessy. Her unstinting love and support (and editorial suggestions) through the period of late nights and weekends I spent writing this book, have made me ever more aware and appreciative of how truly amazing it is to be married to her. 

About the Reviewer

Josh Kurz is a Technical Architect at Turner Broadcasting System. He has written a book on AngularJS, called Mastering AngularJS Directives, and he has contributed to many open source projects.

I would like to thank my baby girl Evelyn for being the sweetest girl in the world.

www.PacktPub.com

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.

Why subscribe?

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

Preface

Angular 2 is here, and we are super exited! This book allows us to reach out to you and lend a helping hand in your quest to learn Angular 2.

While the growth of Angular 1 was organic, the same cannot be said about Angular 2. It rides on the popularity of its predecessor and has already generated phenomenal interest among the developer community. Everyone expects a super awesome future proof framework! And we believe Angular 2 has taken steps in the right direction, which will make it the ubiquitous platform for web and mobile development.

If you are an Angular 1 developer, then there is loads of exciting stuff to learn, and for developers getting started there is a whole new world to explore.

Getting started with Angular 2 can be overwhelming even for a seasoned Angular 1 developer. Too many terms will be thrown at you, such as TypeScript, Transpiler, Shim, Observable, Immutable, Modules, Exports, Decorators, Components, Web Component, Shadow DOM, and more. But relax! We are trying to embrace the modern web and everything new here is to make our life easier. A number of these concepts are not specific to Angular itself but highlight the direction in which web platform development is moving. We will try our best to present these concepts in a clear and concise manner, helping everyone understand how these pieces fit into this big ecosystem.

Learning by examples has its advantages; you immediately see the concept explained in action. This book follows the same pattern as its predecessor. Using the Do It Yourself (DIY) approach, we build multiple simple and complex applications using Angular 2.

Readers coming from the previous version

Angular 2 is a completely new framework and the only thing that it shares with its predecessor is its name! Very few Angular 1 core concepts have made it to Angular 2. Given this fact, this book too is a complete rewrite with all new content. We may be building the same application, but this time we build it using Angular 2.

Why a new version of Angular?

To be frank, that is a question that many Angular developers have asked since Angular 2 was first announced at the ng-europe conference in October 2014. Angular 1 is a hugely popular JavaScript framework.  Over 1 million developers worldwide have used it. Many of them have contributed add-ons/extensions that enhance and strengthen the framework. So why is there a need for a different, new version?

There are several answers to that question. But fundamentally, they all revolve around the fact that Angular 1 is six years old – which is a lifetime in terms of web technology.  For example, Angular 1 predates much of what has developed around mobile technology.  In addition, a new version of JavaScript (ES2015) was approved in 2015 that revolutionizes JavaScript programming. And finally, Angular1 was not designed for use with emerging web standards such as Web Components.

With newer frameworks such as Facebook's React that have been engineered to maximize performance and emphasize mobile-first development, the need for change became more compelling. Angular 2 responds to this challenge by adopting the latest web technologies and incorporating them into a framework for the modern browser.

Angular 2 design

Highlighting some of what is not in Angular 1 leads logically to what the design of Angular 2 is all about. Angular 2 has a mobile-first design. It is therefore engineered for a small footprint, meaning that the data that flows from the server to the browser is minimized as much as possible. The framework itself has been broken into a collection of modules so that only the code needed to run the application is loaded. Moreover, a simplified and more coherent syntax makes it easier to learn and also provides better support for tooling and automation.

Each of the emerging technologies being used in Angular 2 provides key ingredients for realizing these goals. Web Components enable Angular 2 applications to be built out of reusable building blocks that encapsulate their internal logic. ES2015 provides classes and a solid system for loading Angular modules. TypeScript brings types that enable a simpler and more robust syntax for building large-scale applications.

Why use TypeScript?

The examples in this book all use TypeScript. As mentioned, Angular2 allows us to write code in both ES5 (standard JavaScript) and ES2015, along with TypeScript. There are several reasons why we chose TypeScript. To start with, the Angular 2 team itself is using TypeScript to build the framework. Angular 2 code written in TypeScript is far terser than the alternatives. The use of TypeScript also enables IDEs to provide better IntelliSense and code completion support than what is available for JavaScript.

One final point – we think it is easier to learn about Angular 2 using TypeScript. Since this book is about teaching you this new technology, it seemed to be the best selection for the widest audience. As a superset of JavaScript, it offers JavaScript developers an easy migration path to working with types in their Angular applications. And for those developers who are moving to Angular 2 from more traditional object-oriented languages, it offers the familiarity of types and classes.

What this book covers

Chapter 1, Getting Started, introduces you to the Angular framework. We create a super simple app in Angular that highlights some core features of the framework.

Chapter 2, Building Our First App - 7 Minute Workout, teaches us how to build our first real Angular app. In the process, we learn more about one of the primary building blocks of Angular – components. We are also introduced to Angular’s templating constructs, its data binding capabilities and Angular services.

Chapter 3, More Angular 2 – SPA, Routing, and Data Flows in Depth, covers the routing constructs in the framework where we build multiple pages for a 7 Minute Workout. The chapter also explores a number of patterns around inter-component communication.

Chapter 4, Building Personal Trainer, introduces a new exercise where we morph the 7 Minute workout into a generic Personal Trainer app. This app has the ability to create new workout plans other than the original 7 Minute Workout. This chapter covers Angular’s form capabilities, and how we can use them to build custom workouts.

Chapter 5, Supporting Server Data Persistence, deals with saving and retrieving workout data from the server. We augment Personal Trainer with persistence capabilities as we explore Angular's HTTP client library and how it uses RxJS Observables.

Chapter 6, Angular 2 Directives in Depth, goes deep into the inner workings of Angular 2 directives and components. We build a number of directives to support Personal Trainer.

Chapter 7, Testing Personal Trainer, introduces you to the testing world in Angular. You build a suite of unit and end-to-end tests that verify the working of Personal Trainer.

Chapter 8, Some Practical Scenarios, provides some practical tips and guidance around scenarios that we might encounter while developing apps on this framework. We cover scenarios such as authentication and authorization, localization, performance, and the most important case, migrating apps from Angular 1 to Angular 2.

What you need for this book

We will be building our apps in the TypeScript language, therefore it would be preferable if you have an IDE that makes development with TypeScript easy. IDEs such as Atom, Sublime, WebStorm, and Visual Studio (or VS Code) are great tools for this purpose.

All the code enlisted in this book is written and tested for Angular 2.0.0. 

Who this book is for

This book is for readers with no prior experience in Angular. We start from Angular 2 basics and gradually build your understanding of the framework by working through the multiple exercises in the book.

To get the most out of this book, you should have experience in developing on web platforms using HTML, CSS, JavaScript, and a little bit of TypeScript. Angular 1 experience may be advantageous but not necessary for this book.

If you lack TypeScript experience, we highly recommend you visit the TypeScript website: http://www.typescriptlang.org and look at the tutorial, handbook, and samples. For a JavaScript developer, it does not take much time to get up and running with TypeScript.

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: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

@Directive({ selector: '[a2beBusyIndicator]', }) export class BusyIndicator { constructor(private _control: NgControl) { } }

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

<div class="panel-body"> {{description}} </div> <div class="panel-body"> {{steps}} </div>

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

npm install -g angular2

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 shortcuts in this book are based on the Mac OS X 10.5+ scheme."

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 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.

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

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Angular2-By-Example-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Additionally, the code bundle written by the authors is available on GitHub in the following repository link: https://github.com/chandermani/angular2byexample.

Downloading the color images of this book

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/Angular2ByExampleSecondEdition_ColorImages.pdf.

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

Developing applications in JavaScript is always a challenge. Due to its malleable nature and lack of type checking, building a decent-sized application in JavaScript is difficult. Moreover, we use JavaScript for all types of processes, such as user interface (UI) manipulation, client-server interaction, and business processing/validations. As a result, we end up with spaghetti code that is difficult to maintain and test.

Libraries, such as jQuery, do a great job of taking care of various browser quirks and providing constructs that can lead to an overall reduction in the lines of code. However, these libraries lack any structural guidance that can help us when the codebase grows.

In recent years, JavaScript frameworks have emerged to manage this complexity. Many of these frameworks, including earlier versions of Angular, use a design pattern called Model-View-Controller to separate the elements of the application into more manageable pieces. The success of these frameworks and their popularity in the developer community have established the value of using this pattern.

Web development, however, is constantly evolving and a lot has changed since Angular was first introduced in 2009. Technologies such as Web Components, the new version of JavaScript (ES2015), and TypeScript have all emerged. Taken together, they offer the opportunity to build a new, forward-looking framework. And with this new framework comes a new design pattern—the component pattern.

This chapter is dedicated to understanding the component pattern and how to put it into practice as we build a simple app using Angular.

The topics that we will cover in this chapter are as follows:

Angular basics: We will briefly talk about the component pattern that is used to build Angular applicationsBuilding our first Angular app: We will build a small game, Guess the Number!, in AngularAn introduction to some Angular constructs: We will review some of the constructs that are used in Angular, such as interpolation, expressions, and the data binding syntaxChange detection: We will discuss how change detection is managed in an Angular appApp initialization: We will talk about the app initialization process in Angular; this is also known as bootstrappingTools and resources: Lastly, we will provide some resources and tools that will come in handy during Angular development and debugging

Angular basics

Let's get started by looking at how Angular implements the component pattern.

The component pattern

Angular applications use the component pattern. You may not have heard of this pattern, but it is all around us. It is used not only in software development but also in manufacturing, construction, and other fields. Put simply, it involves combining smaller, discrete building blocks into larger finished products. For example, a battery is a component of an automobile.

In software development, components are logical units that can be combined into larger applications. Components tend to have internal logic and properties that are shielded or hidden from the larger application. The larger application then consumes these building-blocks through specific gateways, called interfaces, which expose only what is needed to make use of the component. In this way, the component's internal logic can be modified without affecting the larger application, as long as the interfaces are not changed.

Getting back to our battery example, the car consumes the battery through a series of connectors. If the battery dies, however, it can be replaced by an entirely new battery, as long as that battery has the same connectors. This means that the builder of the car does not have to worry about the internals of the battery, which simplifies the process of building the car. Even more importantly, the car owner does not have to replace his or her car every time the battery dies.

To extend the analogy, manufacturers of batteries can market them for a range of different vehicles, for example, ATVs, boats, or snowmobiles. So the component pattern enables them to realize even greater economies of scale.

Using the component pattern in web applications

As web applications continue to become more sophisticated, the need to be able to construct them out of smaller and discrete components becomes more compelling. Components allow applications to be built in a way that prevents them from becoming messes of spaghetti code. Instead, component-based design allows us to reason about specific parts of the application in isolation from the other parts, and then we can stitch the application together into a finished, whole through agreed-upon points of connection.

Also, maintenance costs are less because each component's internal logic can be managed separately without affecting the other parts of the application. And putting applications together using self-describing components makes the application easier to understand at a higher level of abstraction.

Why weren't components used before in Angular?

If this idea makes so much sense, why was the component pattern not adopted in earlier versions of Angular? The answer is that the technologies that existed when Angular was first released did not fully support the implementation of this pattern in web applications.

Earlier versions of Angular, however, made substantial steps in the direction of enabling more intelligent web application design and organization. For example, they implemented the MVC pattern, which separates an application into a model, view, and controller (you will see the use of the MVC pattern continuing within the components that we will build in Angular).

With the MVC pattern, the model is the data, the view is a web page (or a mobile app screen or even a Flash page), and the controller populates the view with data from the model. In this way, separation of concerns is achieved. Following this pattern along with an intelligent use of directives will get you pretty close to components.

So, the earlier versions of Angular allowed applications to be designed and built more logically. However, this approach was limited by the fact that the technologies used were not truly isolated. Instead, they all ended up being rendered without any true separation from other elements on the screen.

What's new that enables Angular to use this pattern?

By contrast, the newest version of Angular embraces recently emerging technologies, which make it possible to implement the component pattern more fully. These technologies include Web Components, ES2015 (the new version of JavaScript), and TypeScript. Let's discuss what each of these technologies brings to the mix that makes this possible.

Web Components

Web Components is an umbrella term that actually covers four emerging standards for web browsers:

Custom elementsShadow DOMTemplatesHTML imports

Note

More information on Web Components can be found at http://webcomponents.org.

Let's now discuss each of these in detail:

Custom elements enable new types of element to be created other than the standard HTML tag names such as <div> and <p>. The ability to add custom tags provides a location on the screen that can be reserved for binding a component. In short, this is the first step towards separating a component from the rest of the page and making it possible to become truly self-contained.Shadow DOM provides a hidden area on the page for scripts, CSS, and HTML. Markup and styles that are within this hidden area will not affect the rest of the page, and equally important they will not be affected by the markup and styles on other parts of the page. Our component can use this hidden area to render its display. So, this is the second step in making our component self-contained.Templates are repeatable chunks of HTML that have tags that can be replaced with dynamic content at runtime using JavaScript. Many JavaScript frameworks already support some form of templating. Web Components standardize this templating and provide direct support for it in the browser. Templates can be used to make the HTML and CSS inside the Shadow DOM used by our component dynamic. So, this is the third step in making our component.The final standard that makes up Web Components is HTML imports. They provide a way to load resources such as HTML, CSS, and JavaScript in a single bundle. Angular does not use HTML imports. Instead, it relies on JavaScript module loading, which we will discuss a little later in this chapter.

Angular and Web Components

Web Components are not fully supported in current web browsers. For that reason, Angular components are not strictly Web Components. It is probably more accurate to say that Angular components implement the design principles behind Web Components. They also make it possible to build components that can run on today's browsers.

Note

At the time of writing this book, Angular supports evergreen browsers, such as Chrome, Firefox, Edge, as well as IE 7 and later. It also has mobile support for Android 4.1 and later. For a list of browsers supported by Angular, visit https://github.com/angular/angular.

Therefore, throughout the rest of this book, we will focus on building Angular components and not Web Components. Despite this distinction, Angular components align closely with Web Components and can even interoperate with them. As browsers begin to support Web Components more fully, the differences between Angular components and Web Components will begin to disappear. So, if you want to begin adopting the Web Component standards of the future, Angular provides you with the opportunity to do so today.

Language support in Angular

You can develop components with ES5, but Angular enhances the ability to develop components by adding support for key features that are found in the latest languages, such as ES2015 and TypeScript.

ES2015

ES2015 is the new version of JavaScript; it was approved in June 2015. It adds many improvements to the language, which we will see throughout this book, but the two that interest us the most at this point are the following:

ClassesModule loading

Classes did not previously exist in JavaScript. The key advantage of using them, now that they do exist, is that they provide a convenient container for the code in our component.

Note

To be clear, JavaScript classes do not introduce something that is completely new. The Mozilla Developer Network (MDN) describes them as

"syntactical sugar over JavaScript's existing prototype-based inheritance. . . [that] provide a much simpler and clearer syntax to create objects and deal with inheritance."

  For more information visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes.

We'll ecplore these throughout the examples in this book. If you have not worked with object-oriented languages, you may not be familiar with classes, so we will cover them as we work through the examples in this chapter.

ES2015 also introduces a new approach to module loading. A module provides a way for JavaScript files to be encapsulated. When they are encapsulated, they do not pollute the global namespace and can interact with other modules in a controlled manner. We will cover modules in more details in later chapters.

Once we have our modules defined, we need a way to load them into our application for execution. Module loading allows us to select just what we need for our application from the modules that make up Angular and other components that we create or use.

Currently, a range of approaches and libraries exists to support module loading in JavaScript. ES2015 adds a new, consistent syntax for loading modules as part of the language. The syntax is straightforward and involves prefixing modules with the export keyword (or using the default export) and then using import to consume them elsewhere in our application.

ES 2015 module loading enables us to combine components into useful bundles or features that can be imported or exported within our applications. In fact, modules are at the core of Angular itself. We will see that modules are used extensively both in Angular itself and in the applications that we are building throughout this book.

Note

It is important to understand that, while Angular uses syntax that has similarities to ES2015 module-loading syntax, Angular modules (which we will discuss a little later in this chapter) are not the same as JavaScript modules. For further details on these differences see the Angular documentation at https://angular.io/docs/ts/latest/guide/architecture.html. From this point on we will be focusing on Angular modules.

Because ES2015 is not fully supported by today's browsers, we will need to convert ES2015 into ES5 in order to use features such as classes and module loading in our applications. We do this through a process called transpilation.

Transpilation is like compilation, except that instead of converting our code into a machine language as compilation does, transpilation converts one type of source code to another type of source code. In this case, it converts ES2015 to ES5. There are several tools called transpilers that enable us to do that. Common transpilers include Traceur and Babel. TypeScript (which we will discuss next) is also a transpiler, and it is the one that we will use for the examples in this book.

Once ES2015 is transpiled to ES5, we can then use a module loader such as SystemJS to load our modules. SystemJS follows the ES2015 syntax for module loading and gives us the ability to do module loading in today's browsers.

TypeScript

TypeScript was created by Microsoft as a superset of JavaScript, which means that it contains the features of ES2015 (such as classes and module loading) and adds the following:

TypesDecorators

Types allow us to mark variables, properties, and parameters in our classes to indicate that they are numbers, strings, Booleans, or various structures such as arrays and objects. This enables us to perform type checking at design time to make sure that the proper types are being used in our application.

Decorators are simple annotations that we can add to our classes using the @ symbol along with a function. They provide instructions (called metadata) for the use of our classes. In the case of Angular, decorators allow us to identify our classes as Angular components. Decorators can specify modules to be used with a component and how to implement various bindings and directives, including attaching an HTML view to the component. We will cover much more about the use of decorators as we go through this book.

Decorators form a part of the ES2017 proposal and are not part of ES2015. They were added to TypeScript as part of a collaboration between Microsoft and Google. As mentioned earlier, TypeScript compiles into ES5, so we are able to use both types and decorators in browsers that do not fully support ES2015 or the proposed standard for decorators.

Note

As mentioned previously, it is not necessary to use either ES2015 or TypeScript with Angular. However, we think that you will see the advantages of using them as we work through the examples in this book.

Putting it all together

By following the Web Component standards and adding support for ES2015 and TypeScript, Angular gives us the ability to create web applications that implement the component design pattern. These components help realize the vision behind the standards of building large-scale applications through collections of self-describing and self-contained building blocks.

We hope you will see in the examples in this book that Angular enables components to be constructed in a straightforward and declarative way that makes it easier for developers to implement them. As we proceed through the examples in this book, we will highlight where each of these technologies is being used.

Angular modules

Components are the basic building block of an Angular application. But how do we then organize these building blocks into complete applications? Angular modules provide the answer to this question. They enable us to combine our components into reusable groups of functionality that can be exported and imported throughout our application. For example, in a more sophisticated application we would want to have modules for things such as authentication, common utilities, and external service calls. At the same time, modules enable us to group features within an application in a way that allows us to load them on demand. This is called lazy loading, a topic we will cover in Chapter 4, Building Personal Trainer.

Each Angular application will have one or more modules that contain its components. Angular has introduced NgModule as a way to conveniently specify the components that make up a module. Every Angular application must have at least one of these modules—the root module.

Note

Angular itself is built as modules that we import into our application. So you will see the use of modules all over as you build Angular apps.

The basic steps to building Angular applications

To sum up: at a basic level, you will see that to develop applications in Angular, you will do the following:

Create components.Bundle them into modules.Bootstrap your application.

The best way to understand Angular and the component design pattern is by seeing it in action. Hence, we are going to build our first Hello World app in Angular. This app will help you become familiar with the Angular framework and see the component design pattern in action.

Let's get started doing that.