O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Angular 2 By Example

Book Description

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 ‘Guess the Number’ game, which serves as a platform to launch you into the world of Angular. Next, you will learn to construct a popular ‘7-Minute Workout’ app, covering the building blocks of Angular. The final app, ‘Personal Trainer’ morphs the existing ‘7-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.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

Table of Contents

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