41,99 €
A definitive guide on frontend development with Angular from design to deployment
If you have been burnt by unreliable JavaScript frameworks before, you will be amazed by the maturity of the Angular platform. Angular enables you to build fast, efficient, and real-world web apps. In this Learning Path, you'll learn Angular and to deliver high-quality and production-grade Angular apps from design to deployment.
You will begin by creating a simple fitness app, using the building blocks of Angular, and make your final app, Personal Trainer, by morphing the workout app into a full-fledged personal workout builder and runner with an advanced directive building - the most fundamental and powerful feature of Angular.
You will learn the different ways of architecting Angular applications using RxJS, and some of the patterns that are involved in it. Later you’ll be introduced to the router-first architecture, a seven-step approach to designing and developing mid-to-large line-of-business apps, along with popular recipes. By the end of this book, you will be familiar with the scope of web development using Angular, Swagger, and Docker, learning patterns and practices to be successful as an individual developer on the web or as a team in the Enterprise.
This Learning Path includes content from the following Packt products:
If you're a JavaScript or frontend developer looking to gain comprehensive experience of using Angular for end-to-end enterprise-ready applications, this Learning Path is for you.
Chandermani Arora is a software craftsman, with love for technology and expertise on web stack. With years of experience, he has architected, designed, and developed various solutions for Microsoft platforms. He has been building apps on Angular 1 since its early days. Having a passion for the framework every project of his has an Angular footprint. He tries to support the platform in every possible way by writing blogs on various Angular topics or helping fellow developers on StackOverflow, where he is an active member on the Angular channel. He also authored the first edition of this book. Kevin Hennessy is a Senior Software Engineer with Applied Information Sciences. He has 20 years' 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. He has spoken about Angular at the All Things Open Conference. Christoffer Noring is a software developer with more than 10 years of experience. He has successfully delivered software for different industries, ranging from telecom to aviation. Throughout his career, he has worked on everything, right from databases to frontends. He is very passionate about community and sharing knowledge, which is why he frequently speaks on topics ranging from TDD, React, and NativeScript to Angular. He also writes books and blogs frequently. He holds the title of Google Developer Expert in web technologies and AngularJS/Angular. He is also a Telerik Developer Expert in the mobile framework NativeScript. Christoffer currently works for McKinsey as a fullstack developer. He is the author and maintainer of the book RxJS Ultimate, which aims to be a free resource to help the community. Doguhan Uluca is a software development expert for Excella Consulting in Washington, DC. He is the founder and director of the polyglot Tech Talk DC meetup and the creator of the DC Full Stack Web Summit conference. Doguhan has been published on DevPro and ACM. He is a speaker at international conferences, such as Ng-Conf, CodeStock, deliver:Agile and Agile XP. He is a full-stack JavaScript, Agile, and cloud engineering practitioner. Doguhan is an active contributor to the open source community, with libraries and tools published for JavaScript, Angular, Node, and MongoDB.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 717
Veröffentlichungsjahr: 2018
Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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: December 2018 Production Reference: 1191218
Published by Packt Publishing Ltd. Livery Place, 35 Livery Street Birmingham, B3 2PB, U.K.
ISBN 978-1-78995-956-7
www.packtpub.com
Chandermani Arora is a software craftsman, with love for technology and expertise on web stack. With years of experience, he has architected, designed, and developed various solutions for Microsoft platforms. He has been building apps on Angular 1 since its early days. Having a passion for the framework every project of his has an Angular footprint.
He tries to support the platform in every possible way by writing blogs on various Angular topics or helping fellow developers on StackOverflow, where he is an active member on the Angular channel. He also authored the first edition of this book.
Kevin Hennessy is a Senior Software Engineer with Applied Information Sciences. He has 20 years' 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. He has spoken about Angular at the All Things Open conference.
Christoffer Noring, a software developer with over 10 years' experience, has successfully delivered software for industries ranging from telecom to aviation. He has worked on everything from databases to frontend. Frequently speaking on TDD, React, NativeScript, RxJS, and Angular, he writes books and blogs and holds the title of Google Developer Expert in Web Technologies and Angular.
Currently working for McKinsey as a full stack developer, he's the author and maintainer of RxJS Ultimate, and he has coauthored Learning Angular - Second Edition, a Packt title.
Doguhan Uluca is a software development expert for Excella Consulting in Washington, DC. He is the founder and director of the polyglot Tech Talk DC meetup and the creator of the DC Full Stack Web Summit conference. Doguhan has been published on DevPro and ACM. He is a speaker at international conferences, such as Ng-Conf, CodeStock, deliver:Agile and Agile XP. He is a full-stack JavaScript, Agile, and cloud engineering practitioner. Doguhan is an active contributor to the open source community, with libraries and tools published for JavaScript, Angular, Node, and MongoDB.
Phodal Huang is a developer, creator, and author. He works in ThoughtWorks as a Senior Consultant, and focuses on IoT and frontend. He is the author of Design IoT System and Growth: Thinking in Full Stack in Chinese.
He is an open source enthusiast, and has created a series of projects in GitHub. After daily work, he likes to reinvent some wheels for fun. He created the micro-frontend framework Mooa for Angular. You can find out more wheels on his GitHub page, /phodal.
He loves designing, writing, hacking, traveling, you can also find out more about him on his personal website at phodal(dot)com.
Mashhood Rastgar is the founder and technical lead at Recurship, which is a JavaScript consultancy based in Karachi, Pakistan. He is also part of the Google Developer Experts for Web and Angular. Mashhood works startups working in EU and USA, to help them crawl through the technical maze and quickly build amazing products focused around the problems they are trying to solve. He specializes in using the latest technologies available to identify the best solutions. He is also a frequent international and local speaker at different web conferences.
Vinci Rufus is a Google Developer Expert and Senior Director with SapientRazorfish. He consults clients and teams on frontend architecture, mobile strategy, and user experience, primarily in the areas of content and commerce. His areas of interest involve progressive web apps, Angular, React, and web components. He is an author of AngularJS Web Application Development Blueprints.
Sachin Ohri is a technology architect with a keen interest in web-based technologies. He has been writing web applications for more than a decade, with technologies such as .NET, JavaScript, Durandal, Angular, and TypeScript. He works on providing technical solutions, including architectural design, technical support, and development expertise, to Fortune 500 companies. He holds various Microsoft certifications, such as Microsoft Azure Architect, Microsoft ASP.NET MVC web application, and Microsoft Programming with C#.
Andrew Leith Macrae first cut his programming teeth on an Apple IIe, poking bytes into the RAM. Over the years, he has developed interactive applications with Hypercard, Director, Flash, and more recently, Adobe AIR for mobile. He has also worked with HTML since there was HTML to work with and is currently working as a senior frontend developer at The Learning Channel, using Angular 4 with TypeScript.
Wyn B. Van Devanter is currently a managing consultant and senior developer with Excella, an Agile tech firm. He has experience in various industries and government with architecture, design, and implementation of software, largely with web-based applications. He also works heavily with DevOps, cloud, and container-based architectures and strives to be a good software craftsman using XP practices. He enjoys being involved in the community and regularly speaks and conducts workshops at events around the region. Wyn likes playing music, skiing, and conversations of intrigue.
Brendon Caulkins is a DC-based full stack developer at Excella. His focus is Java, but he still harbors a secret love for PHP. He holds a computer engineering degree from Purdue University (Boiler Up!) and refuses to give up playing with Legos. He has nearly a decade of hardware environmental testing and software product testing experience and is really, really good at breaking things. He is also an award-winning painter of tiny toy soldiers and goes by the name Plarzoid on the interwebs.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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.
Title Page
Copyright
Building Large-Scale Web Applications with Angular
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
About Packt
Why subscribe?
PacktPub.com
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Building Our First App - 7 Minute Workout
What is 7 Minute Workout?
Downloading the code base
Setting up the build
Angular CLI
Code transpiling
Organizing code
Feature folders
The 7 Minute Workout model
First feature module
App bootstrapping
Exploring Angular modules
Comprehending Angular modules
Our first component - WorkoutRunnerComponent
Component lifecycle hooks
Building the 7 Minute Workout view
The Angular binding infrastructure
Interpolations
Property binding
Property versus attribute
Property binding continued...
Interpolation syntactic sugar over property binding
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
Learning more about an exercise
Adding descriptions and video panels
Component with inputs
Structural directives
The ever-so-useful NgForOf
Asterisk (*) in structural directives
NgForOf performance
Angular security
Trusting safe content
OnChange life cycle event
Formatting exercise steps with innerHTML binding
Displaying the remaining workout duration using pipes
Angular pipes
Pipe chaining
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
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 life cycle events
Sibling component interaction using events and template variables
Summary
Personal Trainer
Personal Trainer requirements
Getting started with the code for Personal Trainer
Using the Personal Trainer model in Workout Builder services
The Personal Trainer layout
Personal Trainer navigation with routes
Getting started with Personal Trainer navigation
Introducing child routes to Workout Builder
Adding the child routing component
Updating the WorkoutBuilder component
Updating the Workout Builder module
Updating App Routing module
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 resolve route guard
Implementing the Workout component continued...
Implementing the Workout template
Angular forms
Template-driven and reactive 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
Reactive forms
Getting started with reactive 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
Configuration options for running validation
Summary
Supporting Server Data Persistence
Angular and server interactions
Setting up the persistence store
Seeding the database
The basics of the HTTPClient module
Personal Trainer and server integration
Loading exercise and workout data
Loading exercise and workout lists from a server
Adding the HTTPClient module and RxJS to our project
Updating workout-service to use the HTTPClient module and RxJS
Modifying getWorkouts() to use the HTTPClient 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
Updating the resolvers
Fixing the Workout and Exercise components
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
Angular Directives in Depth
Building a remote validator directive
Validating workout names using async validators
Building a busy indicator directive
Injecting optional dependencies with the @Optional decorator
Implementation one – using renderer
Angular renderer, the translation layer
Host binding in directives
Property binding using @HostBinding
Attribute binding
Event binding
Implementation two - 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
1.21 Gigawatt - Flux Pattern Explained
Core concepts overview
A uniform data flow
Action – capture the intent
Dispatcher – the spider in the web
Listening to the dispatcher
The store – managing state, data retrieval, and callbacks
The view
Demoing a uniform data flow
Creating a selection view
Adding the dispatcher
Adding the store
Adding a selected view
Running the demo
Adding more actions to our flow
Cleaning up the view
Cleaning up the store
Adding EventEmitter
Adding to and cleaning up the register method
Further improvements
Adding immutability
Summarizing
Adding AJAX calls
An even bigger solution
Summary
Functional Reactive Programming
Recursion
No more loops
Reoccurring pattern
Summarise
Count
Width
Asynchronous data streams
Comparing lists to async streams – preparing for RxJS
Combining the functional programming paradigm with streams
Projection
Filtering
Combining mindsets
Summary
Manipulating Streams and Their Values
Starting out
Understanding operators
Stream in a stream
AJAX
fetch()
ajax() operator
Cascading calls
A deeper look
Creation operators
of() operator
from() operator
range() operator
fromEvent() operator
Combination
merge() operator
combineLatest()
zip()
concat()
Mathematical
max
min
sum
Time
interval() operator
timer() operator
delay() operator
sampleTime() operator
debounceTime() operator
Grouping
buffer() operator
bufferTime() operator
Thinking in streams
Summary
RxJS Advanced
Hot, cold, and warm Observables
Making a stream hot
Warm streams
Subjects
Using Subject for cascading lists
BehaviorSubject
ReplaySubject
AsyncSubject
Error handling
Catch and continue
Ignoring the error 
Retry
Advanced Retry
Marble testing
Set up
Writing your first marble test
Fleshing out with more tests
Pipeable operators
Creating reusable operators with let()
Shifting to pipeable operators
Summary
Create a Local Weather Web Application
Planning a feature road map using Waffle
Setting up a Waffle project
Creating issues for your Local Weather app
Crafting UI elements using components and interfaces
Adding an Angular component
Define your model using interfaces
Using Angular Services and HttpClient to retrieve data
Creating a new Angular Service
Inject dependencies
Discover OpenWeatherMap APIs
Storing environment variables
Implementing an HTTP GET operation
Retrieving service data from a component
Transform data using RxJS
Understanding Reactive programming
Implementing Reactive transformations
Summary
Prepare Angular App for Production Release
Null guarding in Angular
Property initialization
Safe navigation operator
Null guarding with *ngIf
Containerizing the app using Docker
Installing Docker
Setting up Docker scripts
Docker extension in VS Code
NPM Scripts in VS Code
Deploying containerized app
Zeit Now
Configuring the Now CLI tool
Deploying
Summary
Enhance Angular App with Angular Material
Adding Material Components to your app
Angular Material schematics
Modifying landing page with Material Toolbar
Representing weather in Material Card
Accessibility
Card header and content
Material typography
Applying typography
Updating the tagline as center-aligned caption
Updating Current Weather card layout
Implementing Layout Scaffolding
Aligning elements
Styling elements
Fine-tuning styles
Tweaking to match design
Updating unit tests
Updating Angular Material
Updating Angular Material
Summary
Create a Router-First Line-of-Business App
Angular cheat sheet
Binding
Built-in directives
Common pipes
Starter commands, major components, and CLI scaffolds
Configure Angular CLI autocomplete
Router-first architecture
Creating LemonMart
Creating a Router-first app
Configuring Angular.json and Package.json
Configuring Material and Styles
Designing LemonMart
Identifying user roles
Identifying high-level modules with site map
Generating router-enabled modules
Designing the home route
Setting up default routes
RouterLink
Router outlet
Branding, Custom, and Material Icons
Branding
Color palette
Implementing browser manifest and icons
Custom icons
Material icons
Angular Augury
Component Tree
Break point debugging
Router Tree
NgModules
Submodules with lazy loading
Configuring submodules with components and routes
Eager loading
Lazy loading
Completing the walking skeleton
Manager module
User module
POS and inventory modules
POS module
Inventory module
Inspect router tree
Common Testing Module
Summary
Continuous Integration and API Design
Continuous Integration
Containerizing build environment
Builder
Debugging build environment
Tester
Configuring a headless browser for Angular
Configuring testing environment
Web server
CircleCI
Code coverage report
API design
Designing around major data components
Defining entities
Swagger
Defining a Swagger YAML file
Creating a Swagger server
OpenAPI 3.0 with unofficial tooling
Swagger 2.0 with official tooling
Enable Cross-Origin Resource Sharing (CORS)
Verifying and publishing Swagger server
Summary
Design Authentication and Authorization
Wrapping up mock-ups
Design authentication and authorization workflow
Add auth service
Implement a basic authentication service
Implementing the login component
Conditional navigation
Common validations
UI service
Caching with cookie and localStorage
JSON Web Token life cycle
HTTP interceptor
Side navigation
Log out
Role-based routing after login
Router Guards
Auth Guard
Auth Service Fake and Common Testing Providers
Summary
Angular App Design and Recipes
User class and object-oriented programming
Reusing components
User profile with multi-step auth-enabled responsive forms
Form groups
Stepper and responsive layout
Calculated properties and DatePicker
Type ahead support
Dynamic form arrays
ViewUser component
Review component and Save form
Resolve guard
Reusable component with binding and route data
Master/detail view auxiliary routes
Data table with pagination
Updating Unit Tests
Summary
Highly-Available Cloud Infrastructure on AWS
Right-sizing infrastructure
Optimizing instance
Simple load testing
Deploy to AWS ECS Fargate
Configuring ECS Fargate
Creating a Fargate Cluster
Creating container repository
Creating task definition
Creating elastic load balancer
Creating cluster service
Configuring the DNS
Getting the DNS Name
Prep Angular app
Adding npm Scripts for AWS
Publish
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
If you have been burnt by unreliable JavaScript frameworks before, you will be amazed by the maturity of the Angular platform. Angular enables you to build fast, efficient, and real-world web apps. In this Learning Path, you'll learn Angular and to deliver high-quality and production-grade Angular apps from design to deployment.
You will begin by creating a simple fitness app, using the building blocks of Angular, and make your final app, Personal Trainer, by morphing the workout app into a full-fledged personal workout builder and runner with advanced directive building - the most fundamental and powerful feature of Angular.
You will learn the different ways of architecting Angular applications using RxJS, and some of the patterns that are involved in it. Later you’ll be introduced to the router-first architecture, a seven-step approach to designing and developing mid-to-large line-of-business apps, along with popular recipes. By the end of this book, you will be familiar with the scope of web development using Angular, Swagger, and Docker, learning patterns and practices to be successful as an individual developer on the web or as a team in the Enterprise.
This Learning Path includes content from the following Packt products:
Angular 6 by Example by Chandermani Arora, Kevin Hennessy
Architecting Angular Applications with Redux, RxJS, and NgRx by Christoffer Noring
Angular 6 for Enterprise-Ready Web Applications by Doguhan Uluca
If you’re a JavaScript or frontend developer looking to gain comprehensive experience of using Angular for end-to-end enterprise-ready applications, this Learning Path is for you.
Chapter 1, Building Our First App – 7 Minute Workout, teaches us how to build our first real Angular app. In the process, we will learn more about one of the primary building blocks of Angular, components. We will also be introduced to Angular’s templating constructs, databinding capabilities, and services.
Chapter 2, Personal Trainer, introduces a new exercise where we morph the 7 Minute workout into a generic Personal Trainer app. This app has the capability 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 3, 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 4, Angular Directives in Depth, goes deep into the inner workings of Angular directives and components. We build a number of directives to support Personal Trainer.
Chapter 5, 1.21 Gigawatt – Flux Pattern Explained, teaches what the Flux pattern is and what concepts it consists of. It shows how to implement the Flux pattern using stores, a dispatcher, and several views.
Chapter 6, Functional Reactive Programming, drills down into certain properties of functional programming, such as higher-order functions, immutability, and recursion. Furthermore, we look at how to make code reactive and what reactive means.
Chapter 7, Manipulating Stream and Their Values, focuses a lot on educating the reader on operators, the thing that gives RxJS its power. The reader should leave this chapter with a lot more knowledge about how to manipulate data as well as Observables.
Chapter 8, RxJS Advanced, goes deeper and tries to explain more advanced concepts in RxJS, such as hot and cold Observables, subjects, error handling, and how to test your RxJS code with Marble testing.
Chapter 9, Create a Local Weather Web Application, introduces the Kanban method of software development with easy-to-use design tools used to communicate ideas. It also covers Angular fundamentals, unit testing, and leveraging CLI tools to maximize your impact.
Chapter 10, Prepare Angular App for Production Release, covers how to use containerization with Docker to enable cloud deployments.
Chapter 11, Enhance Angular App with Angular Material, introduces you to Angular material and explains how to use it to build great-looking apps.
Chapter 12, Create a Router-First Line-of-Business App, focuses on the Router-first architecture, a seven-step approach to the design and development of mid-to-large applications.
Chapter 13, Continuous Integration and API Design, goes over continuous integration using CircleCI and early integration with backend APIs using Swagger.
Chapter 14, Design Authentication and Authorization, dives into authentication- and authorization-related patterns in Angular and RESTful applications.
Chapter 15, Angular App Design and Recipes, contains recipes commonly needed for line-of-business applications.
Chapter 16, Highly-Available Cloud Infrastructure on AWS, moves beyond application features to go over provisioning a highly-available cloud infrastructure on AWS.
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.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit 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 at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
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/chandermani/angular6byexample and https://github.com/PacktPublishing/Architecting-Angular-Applications-with-Redux-RxJs-and-NgRx. The code bundle for the third module is hosted on author's GitHub repository at https://github.com/duluca/local-weather-app and https://github.com/duluca/lemon-mart. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
We will be building a new app in Angular, and in the process, become more familiar with the framework. This app will also help us explore some new capabilities of Angular.
The topics that we will cover in this chapter include the following:
7 Minute Workout problem description
: We detail the functionality of the app that we build in this chapter.
Code organization
: For our first real app, we will try to explain how to organize code, specifically Angular code.
Designing the model
: One of the building blocks of our app is its model. We design the app model based on the app's requirements.
Understanding the data binding infrastructure
: While building the
7 Minute Workout
view, we will look at the data binding capabilities of the framework, which include
property
,
attribute
,
class
,
style
, and
event
bindings.
Exploring the Angular platform directives
: Some of the directives that we will cover are
ngFor
,
ngIf
,
ngClass
,
ngStyle
, and
ngSwitch
.
Cross-component communication with input properties
: As we build nested components, we learn how input properties can be used to pass data from the parent to its child components.
Cross-component communication with events
: Angular components can subscribe to and raise events. We get introduced to event binding support in Angular.
Angular pipes
: Angular pipes provide a mechanism to format view content. We explore some standard Angular pipes and build our own pipe to support conversions from seconds to hh:mm:ss.
Let's get started! The first thing we will do is to define our 7 Minute Workout app.
We want everyone reading this book to be physically fit. Therefore, this book should serve a dual purpose; it should not only stimulate your grey matter but also urge you to look after your physical fitness. What better way to do it than to build an app that targets physical fitness!
7 Minute Workout is an exercise/workout app that requires us to perform a set of 12 exercises in quick succession within the seven-minute time span. 7 Minute Workout has become quite popular due to its bite-sized length and great benefits. We cannot confirm or refute the claims, but doing any form of strenuous physical activity is better than doing nothing at all. If you are interested to know more about the workout, then check out http://well.blogs.nytimes.com/2013/05/09/the-scientific-7-minute-workout/.
The technicalities of the app include performing a set of 12 exercises, dedicating 30 seconds for each of the exercises. This is followed by a brief rest period before starting the next exercise. For the app that we are building, we will be taking rest periods of 10 seconds each. So, the total duration comes out at a little more than seven minutes.
At the end of the chapter, we will have the 7 Minute Workout app ready, which will look something like the following:
The code for this app can be downloaded from the GitHub site (https://github.com/chandermani/angular6byexample) dedicated to this book. Since we are building the app incrementally, we have created multiple checkpoints that map to GitHub branches such as checkpoint2.1, checkpoint2.2, and so on. During the narration, we will highlight the branch for reference. These branches will contain the work done on the app up until that point in time.
So, let's get started!
Remember that we are building on a modern platform for which browsers still lack support. Therefore, directly referencing script files in HTML is out of the question (while common, it's a dated approach that we should avoid anyway). Browsers do not understand TypeScript; this implies that there has to be a process that converts code written in TypeScript into standard JavaScript (ES5). Hence, having a build set up for any Angular app becomes imperative. And thanks to the growing popularity of Angular, we are never short of options.
If you are a frontend developer working on the web stack, you cannot avoid Node.js. This is the most widely used platform for web/JavaScript development. So, no prizes for guessing that most of the Angular build solutions out there are supported by Node. Packages such as Grunt, Gulp, JSPM, and webpack are the most common building blocks for any build system.
For this book and this sample app, we endorse Angular CLI (http://bit.ly/ng6be-angular-cli). A command line tool, it has a build system and a scaffolding tool that hugely simplifies Angular's development workflow. It is popular, easy to set up, easy to manage, and supports almost everything that a modern build system should have. More about it later.
As with any mature framework, Angular CLI is not the only option out there on the web. Some of the notable starter sites plus build setups created by the community are as follows:
Start site
Location
angular2-webpack-starter
http://bit.ly/ng2webpack
angular-seed
https://github.com/mgechev/angular-seed
Let's start with installing Angular CLI. On the command line, type the following:
npm i -g @angular/cli
Once installed, Angular CLI adds a new command ng to our execution environment. To create a new Angular project from the command line, run the following command:
ng new PROJECT-NAME
This generates a folder structure with a bunch of files, a boilerplate Angular application, and a preconfigured build system. To run the application from the command line, execute the following:
ng serve --open
And you can see a basic Angular application in action!
For our 7 Minute Workout app, instead of starting from scratch, we are going to start from a version that is based on the project structure generated by ng new with minor modification. Start with the following steps:
Download the base version of this app from
http://bit.ly/ngbe-base
and unzip it to a location on your machine. If you are familiar with how Git works, you can just clone the repository and check out the
base
branch:
git checkout base
This code serves as the starting point for our app.
Navigate to the
trainer
folder from the command line and execute the command
npm install
from the command line to install the
package dependencies
for our application.
Once npm pulls the app dependencies from the npm store, we are ready to build and run the application. From the command line, enter the following command:
ng serve --open
This compiles and runs the app. If the build process goes fine, the default browser window/tab will open with a rudimentary app page (http://localhost:4200/). We are all set to begin developing our app in Angular!
But before we do that, it would be interesting to know a bit more about Angular CLI and the customization that we have done on the default project template that Angular CLI generates.
Angular CLI was created with the aim of standardizing and simplifying the development and deployment workflow for Angular apps. As the documentation suggests:
It incorporates:
A build system based on
webpack
A
scaffolding tool
to generate all standard Angular artifacts including modules, directives, components, and pipes
Adherence to
Angular style guide
(
http://bit.ly/ngbe-styleguide
), making sure we use community-driven standards for projects of every shape and size
A targeted
linter;
Angular CLI integrates with
codelyzer
(
http://bit.ly/ngbe-codelyzer
), a
static code analysis tool
that validates our Angular code against a set of rules to make sure that the code we write adheres to standards laid down in the Angular style guide
Preconfigured
unit
and
end-to-end
(
e2e
) test framework
And much more!
Imagine if we had to do all this manually! The steep learning curve would quickly overwhelm us. Thankfully, we don't have to deal with it, Angular CLI does it for us.
The tweaks that we have done to the default generated project template are:
Referenced Bootstrap CSS in the
style.css
file.
Upgraded some npm library versions.
Changed the prefix configuration for generated code to use
abe
(short for Angular By Example) from
app
. With this change, all our components and directive selectors will be prefixed by
abe
instead of
app
. Check
app.component.ts
; the
selector
is
abe-root
instead of
app-root
.
While on the topic of Angular CLI and builds, there is something that we should understand before proceeding.
What happens to the TypeScript code we write?
Browsers, as we all know, only work with JavaScript, they don't understand TypeScript. We hence need a mechanism to convert our TypeScript code into plain JavaScript (ES5 is our safest bet). The TypeScript compiler does this job. The compiler takes the TypeScript code and converts it into JavaScript. This process is commonly referred to as transpiling, and since the TypeScript compiler does it, it's called a transpiler.
Interestingly, transpilation can happen at both build/compile time and at runtime:
Build-time transpilation
: Transpilation as part of the build process takes the script files (in our case, TypeScript
.ts
files) and compiles them into plain JavaScript. Angular CLI does build-time transpilation.
Runtime transpilation
: This happens in the browser at runtime. We directly reference the TypeScript files (
.ts
in our case), and the TypeScript compiler, which is loaded in the browser beforehand, compiles these script files on the fly. This is a workable setup only for small examples/code snippets, as there is an additional performance overhead involved in loading the
transpiler
and
transpiling
the code on the fly.
The process of transpiling is not limited to TypeScript. Every language targeted towards the web, such as CoffeeScript, ES2015, (yes JavaScript itself!) or any other language that is not inherently understood by a browser needs transpilation. There are transpilers for most languages, and the prominent ones (other than TypeScript) are tracuer and babel.
The Angular CLI build system takes care of setting up the TypeScript compiler and sets up file watchers that recompile the code every time we make changes to our TypeScript file.
Let's get back to the app we are building and start exploring the code setup.
The advantage of Angular CLI is that is dictates a code organization structure that works for applications of all sizes. Here is how the current code organization looks:
trainer
is the application root folder.
The files inside
trainer
are configuration files and some standard files that are part of every standard node application.
The
e2e
folder will contain end to end tests for the app.
src
is the primary folder where all the development happens. All the application artifacts go into
src
.
The
assets
folder inside
src
hosts static content (such as images, CSS, audio files, and others).
The
app
folder has the app's source code.
The
environments
folder is useful to set configurations for different deployment environments (such as
dev, qa, production
).
To organize Angular code inside the app folder, we take a leaf from the Angular style guide (http://bit.ly/ng6be-style-guide) released by the Angular team.
The style guide recommends the use of feature folders to organize code. With feature folders, files linked to a single feature are placed together. If a feature grows, we break it down further into sub features and tuck the code into sub folders. Consider the app folder to be our first feature folder! As the application grows, app will add sub features for better code organization.
Let's get straight into building the application. Our first focus area, the app's model!
Designing the model for this app requires us to first detail the functional aspects of the 7 Minute Workout app, and then derive a model that satisfies those requirements. Based on the problem statement defined earlier, some of the obvious requirements are as follows:
Being able to start the workout.
Providing a visual clue about the current exercise and its progress. This includes the following:
Providing a visual depiction of the current exercise
Providing step-by-step instructions on how to do a specific exercise
The time left for the current exercise
Notifying the user when the workout ends.
Some other valuable features that we will add to this app are as follows:
The ability to pause the current workout.
Providing information about the next exercise to follow.
Providing audio clues so that the user can perform the workout without constantly looking at the screen. This includes:
A timer click sound
Details about the next exercise
Signaling that the exercise is about to start
Showing related videos for the exercise in progress and the ability to play them.
As we can see, the central themes for this app are workout and exercise. Here, a workout is a set of exercises performed in a specific order for a particular duration. So, let's go ahead and define the model for our workout and exercise.
Based on the requirements just mentioned, we will need the following details about an exercise:
The name. This should be unique.
The title. This is shown to the user.
The description of the exercise.
Instructions on how to perform the exercise.
Images for the exercise.
The name of the audio clip for the exercise.
Related videos.
With TypeScript, we can define the classes for our model.
The Exercise class looks as follows:
export class Exercise { constructor( public name: string, public title: string, public description: string, public image: string, public nameSound?: string, public procedure?: string, public videos?: Array<string>) { } }
For the workout, we need to track the following properties:
The name. This should be unique.
The title. This is shown to the user.
The exercises that are part of the workout.
The duration for each exercise.
The rest duration between two exercises.
The model class to track workout progress (WorkoutPlan) looks as follows:
export class WorkoutPlan { constructor( public name: string, public title: string, public restBetweenExercise: number,
public exercises: ExercisePlan[],
public description?: string) { } totalWorkoutDuration(): number { ... } }
The totalWorkoutDuration function returns the total duration of the workout in seconds.
WorkoutPlan has a reference to another class in the preceding definition, ExercisePlan. It tracks the exercise and the duration of the exercise in a workout, which is quite apparent once we look at the definition of ExercisePlan:
export class ExercisePlan { constructor( public exercise: Exercise, public duration: number) { } }
Let me save you some typing and tell you where to get the model classes, but before that, we need to decide where to add them. We are ready for our first feature.
The primary feature of 7 Minute Workout is to execute a predefined set of exercises. Hence we are going to create a feature module now and later add the feature implementation to this module. We call this module workout-runner. Let's initialize the feature with Angular CLI's scaffolding capabilities.
From the command line, navigate to the trainer/src/app folder and run the following:
ng generate module workout-runner --module app.module.ts
Follow the console logs to know what files are generated. The command essentially:
Creates a new Angular
WorkoutRunnerModule
module inside a new
workout-runner
folder
Imports the newly created module into the main application module app (
app.module.ts
)
We now have a new feature module.
Open the newly generated module definition (workout-runner.module.ts) and look at the generated content. WorkoutRunnerModule imports CommonModule, a module with common Angular directives such as ngIf and ngFor, allowing us to use these common directives across any component/directive defined in WorkoutRunnerModule.
Copy the model.ts file from http://bit.ly/ng6be-2-1-model-ts into the workout-runner folder. Shortly, we will see how these model classes are utilized.
Since we have started with a preconfigured Angular app, we just need to understand how the app starts.
The app bootstrapping process for 7 Minute Workout can be carried out from the src folder. There is a main.ts file that bootstraps the application by calling the following:
platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.log(err));
The heavy lifting is done by the Angular CLI, which compiles the application, includes the script and CSS reference into index.html, and runs the application. We don't need to configure anything. These configurations are part of the default Angular CLI configuration (.angular-cli.json).
We have created a new module and added some model classes to the module folder. Before we go any further and start implementing the feature, let's talk a bit about Angular modules.
As the 7 Minute Workout app grows and we add new components/directives/pipes/other artifacts to it, a need arises to organize these items. Each of these items needs to be part of an Angular module.
A naïve approach would be to declare everything in our app's root module (AppModule), as we did with WorkoutRunnerComponent, but this defeats the whole purpose of Angular modules.
To understand why a single-module approach is never a good idea, let's explore Angular modules.
In Angular, modules are a way to organize code into chunks that belong together and work as a cohesive unit. Modules are Angular's way of grouping and organizing code.
An Angular module primarily defines:
The components/directives/pipes it owns
The components/directives/pipes it makes public for other modules to consume
Other modules that it depends on
Services that the module wants to make available application-wide
Any decent-sized Angular app will have modules interlinked with each other: some modules consuming artifacts from other, some providing artifacts to others, and some modules doing both.
As a standard practice, module segregation is feature-based. One divides the app into features or subfeatures (for large features) and modules are created for each of the features. Even the framework adheres to this guideline as all of the framework constructs are divided across modules:
There is
CommonModule
that aggregates the standard framework constructs used in every browser-based Angular app
There is
RouterModule
if we want to use the Angular routing framework
There is
HtppModule
if our app needs to communicate with the server over HTTP
Angular modules are created by applying the @NgModule decorator to a TypeScript class. The decorator definition exposes enough metadata, allowing Angular to load everything the module refers to.
The decorator has multiple attributes that allow us to define:
External dependencies (using
imports
).
Module artifacts (using
declarations
).
Module exports (using
exports
).
The services defined inside the module that need to be registered globally (using
providers
).
The main application view, called the
root component
, which hosts all other app views. Only the root module should set this using the
bootstrap
property.
This diagram highlights the internals of a module and how they link to each other:
We hope one thing is clear from all this discussion: creating a single application-wide module is not the right use of Angular modules unless you are building something rudimentary.
It's time to get into the thick of the action; let's build our first component.
