41,99 €
Build modern SPAs by learning the latest and powerful features of Angular 5 and TypeScript 2.x
This book is for web developers who want to build the next generation of state-of-the-art mobile and desktop web applications with Angular. This book does not require you to have prior exposure to either Angular 1.x, 2 or 4, although comprehensive knowledge of JavaScript is assumed.
The latest version of Angular comes with a lot of new features that help you to make your applications smaller and faster. This book will show you how to set up an Angular project, and you'll build Angular components right from the beginning.
Moving on, you'll explore and work with the components to build your app. Next, you'll find out more about TypeScript and see how to use it to build apps in the best way possible. You'll then be introduced to the building blocks - Properties, Events, Directives, and Pipes - and how it can be used to implement and enhance the components.
Additionally, you'll be using Angular components to organize your components in a scalable way. Then you'll understand how to get data in your app and add navigation to it. Furthermore, you'll deep dive and work with Forms, Authentication, and see how Material design will help you make your app beautiful in just a few short lines of code. Lastly, you'll see how to use animating components with Angular, and test and debug the app.
All in all, the overall mission is to give you a great start when developing apps using Angular and TypeScript.
This book tells you everything there is to know about getting well-acquainted with Angular without bogging you down. Everything is neatly laid out under clear headings for quick consultation, giving you the information required to understand a concept immediately. You'll also get full coverage of the TypeScript syntax required to follow the examples included.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 558
Veröffentlichungsjahr: 2017
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the 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: May 2016
Second edition: December 2017
Production reference: 1051217
ISBN 978-1-78712-492-9
www.packtpub.com
AuthorsChristoffer Noring
Pablo Deeleman
Copy EditorSafis Editing
ReviewerPablo Deeleman
Project CoordinatorUlhas Kambali
Commissioning EditorAshwin Nair
ProofreaderSafis Editing
Acquisition EditorReshma Raman
IndexerPratik Shirodkar
Content Development EditorNikhil Borkar
GraphicsJason Monteiro
Technical EditorSubhalaxmi Nadar
Production CoordinatorArvindkumar Gupta
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.
Pablo Deeleman is a former UI/UX designer who fell in love with JavaScript and CSS back in 1998, during the good old days of Netscape Navigator and Microsoft Internet Explorer 3. The discovery of Node.js back in 2011 became a turning point in his career, from where he decided to embrace full-time JavaScript-driven development, carving out a career as a JavaScript full stack engineer with special focus on single-page application development.
With sound expertise in libraries and frameworks, such as Backbone.js, Knockout.js, Polymer, React, AngularJs, and Angular, Pablo Deeleman built his career in a wide range of companies encompassing internationally acclaimed tube sites, fintech start-ups, and award-winning gaming and gambling sites. He currently works as a senior frontend engineer and Angular specialist for Red Hat, the multinational company providing open source software products to the enterprise community.
Pablo has also authored Learning Angular 2 (Packt, 2016) and currently lives in sunny and bustling Barcelona, where he fulfills his other great passion: playing piano.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787124924.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Creating Our First Component in Angular
It's just Angular – introducing semantic versioning
Patch change
Minor change
Major change
What about Angular?
A fresh start
Web components
Why TypeScript over other syntaxes?
Setting up our workspace with Angular CLI
Prerequisites
Installation
First app
Testing
Hello Angular
Creating the component
Selector
Template/templateUrl
Telling the module
Setting up a bootstrap file
Diving deeper into Angular components
Component methods and data updates
Going from static to actual data
Adding interactivity to the component
Improving the data output
Summary
IDEs and Plugins
IDEs
Atom
Sublime Text 3
Webstorm
Visual Studio Code
Summary
Introducing TypeScript
Understanding the case for TypeScript
The benefits of TypeScript
Introducing TypeScript resources in the wild
The TypeScript official site
The TypeScript official wiki
Types in TypeScript
String
Declaring our variables – the ECMAScript 6 way
The let keyword
Const
Number
Boolean
Array
Dynamic typing with the any type
Custom type
Enum
Void
Type inference
Functions, lambdas, and execution flow
Annotating types in our functions
Function parameters in Typescript
Optional parameters
Default parameters
Rest parameters
Overloading the function signature
Better function syntax with and scope handing with lambdas
General features
Spread parameter
Template strings
Generics
Classes, interfaces, and class inheritance
Anatomy of a class – constructors, properties, methods, getters, and setters
Constructor parameters with accessors
Interfaces in TypeScript
Extending classes with class inheritance
Decorators in TypeScript
Class decorators
Extending the class decorator function signature
Property decorators
Method decorators
Parameter decorator
Organizing our applications with modules
Internal modules
External modules
ES6 like modules per TypeScript > 1.5
Summary
Implementing Properties and Events in Our Components
A better template syntax
Data bindings with input properties
Some extra syntactic sugar when binding expressions
Event binding with output properties
Input and output properties in action
Setting up custom values declaratively
Communicating between components through custom events
Emitting data through custom events
Local references in templates
Alternative syntax for input and output properties
Configuring our template from our component class
Internal and external templates
Encapsulating CSS styling
The styles property
The styleUrls property
Inline style sheets
Managing view encapsulation
Summary
Enhancing Our Components with Pipes and Directives
Directives in Angular
Core directives
NgIf
NgFor
Advanced looping
Else
Applying style
Interpolation
NgStyle
NgClass
NgSwitch, ngSwitchCase, and ngSwitchDefault
Manipulating template bindings with pipes
The uppercase/lowercase pipe
The decimal, percent, and currency pipes
The decimal pipe
The percent pipe
The currency pipe
The slice pipe
The date pipe
The JSON pipe
The i18n pipes
The i18nPlural pipe
The i18nSelect pipe
The async pipe
Putting it all together in a task list
Setting up our main HTML container
Building our task list table with Angular directives
Toggling tasks in our task list
Displaying state changes in our templates
Embedding child components
Building our own custom pipes
Anatomy of a custom pipe
Imports
Defining our pipe
Registering it
The pure property
A custom pipe to better format time output
Filtering out data with custom filters
Building our own custom directives
Anatomy of a custom directive
Listening to events
Adding input data
Adding more than one input property
A second example – error validation
Building a task tooltip custom directive
A word about naming conventions for custom directives and pipes
Summary
Building an Application with Angular Components
Introducing the component tree
Common conventions for scalable applications
File and ES6 module naming conventions
From facades/barrels to NgModule
Using NgModule
How dependency injection works in Angular
A note on providers
Injecting dependencies across the component tree
Restricting dependency injection down the component tree
Restricting provider lookup
Overriding providers in the injector hierarchy
Extending injector support to custom entities
Initializing applications with bootstrapModule()
Switching between development and production modes
Different modes in Angular CLI
Introducing the app directory structure
Refactoring our application the Angular way
The shared context or store it all in a common module
Services in the shared context
Configuring application settings from a central service
Putting it all together in our shared module
Creating our components
Introduction to life cycle hooks
OnInit - the beginning of it all
OnDestroy - called when a component is removed from a DOM tree
OnChanges - a change has occurred
The timer feature
The tasks feature
Defining the top root component
Summary
Asynchronous Data Services with Angular
Strategies for handling asynchronous information
Asynchronous response - from callbacks to promises
Observables in a nutshell
Reactive functional programming in Angular
The RxJS library
Introducing the HTTP API
Working with headers
Handling errors when performing HTTP requests
Injecting the HttpClient service
A real case study – serving Observable data through HTTP
Leveraging HTTP – refactoring our TaskService to use HTTP service
Using the Angular HTTP service
A stateful TaskService for most scenarios
Further improvements – turning TaskService into a stateful, more robust service
Handling service calls when network connection intermittently goes offline
Introducing the store/feed pattern
Persisting data
Refreshing our service
HttpInterceptor
Creating a mock interceptor
Some best practices
Async operator
Being a good citizen – cleaning up after yourself
Summary
Firebase
Three-way binding versus two-way binding
Some words on storage - the problem with a list
Objects in a list - solving the deletion problem
AngularFire2
The core classes
The admin tools
Defining your database
Adding AngularFire2 to your app
Protecting our app
Authentication - allowing access to the app
Authorization - deciding who gets to access what data, and how
Validation
Working with data - CRUD
Reading data
Changing data
Removing data
Removing an object
Removing an item in a list
Responding to change
Adding authentication
Simple authentication with email/password
Summary
Routing
Adding support for the Angular router
Specifying the base element
Importing and setting up the router module
Defining the routes
Defining a viewport
Building a practical example – setting up the router service
Building a new component for demonstration purposes
Cleaning up the routes
The router directives – RouterOutlet, RouterLink, and RouterLinkActive
Triggering routes imperatively
Handling parameters
Building detail pages – using route parameters
Filtering your data – using query parameters
Advanced features
Child routes
Absolute versus relative navigation
Named outlets
Debugging
Fine-tuning our generated URLs with location strategies
Securing the routes with AuthGuard and CanActivate hook
Resolve<T> – fetching and resolving data before routing
The CanDeactivate – handling cancel and save
Async routing – improving response time
Lazy loading
CanLoad – don't lazy load unless the user has access
Preloading
Summary
Forms in Angular
Template-driven forms
Turning a simple form into a template-driven form
Input field error – from a CSS standpoint
Detecting an error on an input field with named references
Improving the form
Showing errors at the right time
Reactive forms
AbstractControl
Programmatic and dynamic approach
Turning a form into a dynamic form
Adding controls with validation rules
Refactoring – making the code more dynamic
Updating our component form model – using setValue and patchValue
setValue
patchValue
Cleaning up our form creation and introducing FormBuilder
Building your own custom validator
Watching state changes and being reactive
Summary
Angular Material
Material Design
Known implementations
Angular Material
Installation
Our first Angular Material app
Component overview
Buttons
Form controls
Input
Autocomplete
Checkbox
Date picker
Navigation
Menu
Layout
List
Grid list
Popups and modals
Dialog
A more advanced example – sending data to and from your dialog
Data table
Table
Sorting
Pagination
Summary
Animating Components with Angular
Creating animations with plain vanilla CSS
Introducing Angular animations
Our first trigger
Connecting the parts
The wildcard state
The void state
Animation callbacks
Animating components with the AnimationBuilder
Creating a reusable animation directive
Summary
Unit Testing in Angular
Why do we need tests?
The anatomy of a unit test
Introduction to testing in Angular
Configuration and setting up
Angular testing utilities
Introduction to component testing
Component testing with dependencies
Using a stub to replace the dependency
Spying on the dependency method
Async services
Testing pipes
Mocking HTTP responses with HttpClientTestingController
Input and outputs
Testing routing
Testing navigation
Testing routes by URL
Testing route parameters
Testing directives
The road ahead
Introducing code coverage reports in your test stack
Implementing E2E tests
Summary
SystemJS
SystemJS introduction
A flying start with the quickstart repository
Understanding the parts
The essential concepts that makes out any Angular project set up with SystemJS
Starter web page - index.html
Core files - that Angular is dependent on
core-js
zone.js
rxjs
SystemJS - our module loader
Node.js setup - package.json
TypeScript setup
Summary
Webpack with Angular
Core concepts
Loaders
Plugins
Webpack - first project
Improving our project - using a configuration file
Adding more capabilities to our project
Creating several bundles
Setting up Angular with webpack
Common configuration
Dev configuration
Production configuration
Testing
Summary
We have come a long way since 2010, when AngularJS was first released. Internet wasn't really made to be an application platform but one for rendering static pages. This has, of course, changed as developers have started treating it more and more as their main application platform. The promise of reaching billions of people has been too enticing. This meant that the web had to grow up. Different approaches have been tried during the years, such as JSP, GWT, Web Forms for .NET, and so on—approaches that have been more or less successful. What is clear is that when AngularJS showed up, it was greeted as a savior. It made it super easy for everyone to quickly create an application with JavaScript, CSS, HTML, and even use AJAX. It's still a valid choice for building small to medium applications.
The easier something is to use, the more likely it is that people will treat it like ketchup and start adding more and more to it to and use it everywhere. AngularJS was never meant for large enterprise applications. The Internet progressed and more and more features became available in the browser. There was an idea of wanting to incorporate all these new features but also to ensure that AngularJS could be used for really large applications. A decision was taken that it would be easier to start over from scratch and create Angular, the successor of AngularJS. And so, on 14 September 2016, the release version of Angular saw the light of day. Since then major versions of Angular have been produced at a furious pace.
We are now on version 5. This does not mean that Angular core concepts have changed, they have been retained. Certain breaking changes have been introduced along the way, but every major version has firstly corrected bugs, introduced new features, and really aimed at making Angular apps as fast as possible and their footprint as small as possible. This is a worthy goal to have in today's mobile-first world.
This book aims to introduce the reader to all the major facets of Angular, and show you how to build small, medium, and, even, large applications. You don't need much knowledge to get started with Angular applications, but there are many layers to it. As your app grows in size, you will want to care about making it prettier, faster, easier to maintain, and so on. This book is written with that in mind. Take your time reading this book. If you want to read a few chapters and build some apps, do it. If you want to jump straight into the more advanced features, then that is your prerogative.
We hope you will enjoy reading this book as much as we enjoyed writing it
Chapter 1, Creating our First Component inAngular, covers Semantic versioning. This is an important concept to grasp, so you know whether to adopt new releases based on your needs. This chapter also introduces the reader to the Angular CLI and the reader will be taking their first steps into writing an Angular application.
Chapter 2, IDEs and Plugins, introduces you to the most popular IDEs. The most common Angular plugins and snippets are also described to further boost developer productivity.
Chapter 3, Introducing TypeScript, introduces TypeScript, which is the chosen language for coding Angular apps. There is more to TypeScript than just adding types. Your code can be made elegant and more secure, and using the right features will save you from typing quite a lot.
Chapter 4, Implementing Properties and Events in our Components, covers how to send data to components and how to bind methods to them so that the components have the ability to communicate upstream.
Chapter 5, Enhancing our Component with Pipes and Directives, shows how you can make your component more consistent and reusable with the help of pipes and directives.
Chapter 6, Building an Application with Angular Components, dives right into our goal of building a real application. We address how to think and how to use the most common structural directives in order to control how the data should be displayed and act when being manipulated by UI elements.
Chapter 7, Asynchronous Data Services with Angular, introduces the RxJS library, which not only helps us with AJAX but also facilitates reactive application patterns. All things async become one concept under RxJS, the possibilities that this introduces are endless.
Chapter 8, Firebase, explains Firebase, which is a product by Google that allows you to have backend as a service. Firebase lets you focus on building Angular apps while it takes care of almost everything else. The best part is Firebase's reactive nature, which makes chat-like applications as well as collaboration apps a breeze to create.
Chapter 9, Routing, explains the concept of routing, so you can scale your application seamlessly.
Chapter 10, Forms in Angular, covers the two main ways of dealing with forms and user input: template-driven and the reactive approach.
Chapter 11, Angular Material, takes you through Angular Material, which not only offers a beautiful interface but also comes with a bunch of components that will make it a piece of cake to quickly assemble an impressive application.
Chapter 12, Animating Components with Angular, covers how well Angular supports the developer in leveraging and controlling quite advanced animations.
Chapter 13, Unit Testing in Angular, explains unit testing in Angular. The Angular team has really added first-class support for testing, so you, with a very few lines of code, are able to test all the possible constructs your mind can dream up. Everything from component, service, and directives to E2E testing.
Appendix A, SystemJS, covers SystemJS, which is a module loader and used to be the only way to set up an Angular application. It's still a valid way to set up your project. This Appendix will cover the core parts of SystemJS and zoom in on the Angular set up bit in particular.
Appendix B, Webpack with Angular, aims at showing the developer how to set up your Angular project with Webpack. There definitely exists a user base that wants complete control of every aspect of a web project. If that is you, then this appendix is for you.
To really appreciate this book, we assume that you are familiar with HTML, CSS, and JavaScript, to a certain degree, as well as calling services with AJAX. We also assume that you have a fair understanding of REST. Modern web application development has become quite a daunting task, but it is our hope that you will, after having read this book, feel that you understand more about what's going on, and that you will also feel more than able to take on your next web development project using Angular.
As you will spend most of your time writing JavaScript, HTML, or CSS code, we only assume that you have access to a decent text editor. The more accomplished editor you use, the more help you will get, which is why we introduce some plugins and best practices in this book to make your everyday work less painful.
This book is intended for web developers with no prior knowledge of Angular but who are experienced in JavaScript, Node.js, HTML, and CSS and are reasonably familiar with the idea of Single Page Applications.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Angular-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!
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 http://www.packtpub.com/sites/default/files/downloads/LearningAngularSecondEdition_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
When it comes to Angular development, there are some things that are good to know and some things that we need to know to embark on our great journey. One of the things that is good to know is semantic versioning. This is good to know because it is the way the Angular team has chosen to deal with changes. This will hopefully make it easier to find the right solutions to future app development challenges when you go to https://angular.io/ or Stack Overflow and other sites to search for solutions.
Another important, but sometimes painful, topic is that of project setup. It is a necessary evil that needs to be done in the beginning of a project, but getting this right early on can reduce a lot of friction as your application grows with you. Therefore, a large part of this chapter is dedicated to demystifying and enabling you as a developer to save you from future frustrations and migraines.
We will also be able to create our first application at the end of this chapter and get a feel for the anatomy of an Angular application. To sum up, here are the main themes that we will explore in this chapter.
In this chapter, we will:
Learn about semantic versioning, why it matters, and Angular's take on it
Discover how we set up our project using Angular CLI
Create our first application and begin to understand the core concepts in Angular
Using semantic versioning is about managing expectations. It's about managing how the user of your application, or library, will react when a change happens to it. Changes will happen for various reasons, either to fix something broken in the code or add/alter/remove a feature. The way authors of frameworks or libraries use to convey what impact a certain change has is by incrementing the version number of the software.
A production-ready software usually has version 1.0 or 1.0.0 if you want to be more specific.
There are three different levels of change that can happen when updating your software. Either you patch it and effectively correct something. Or you make a minor change, which essentially means you add functionality. Or lastly you make a major change, which might completely change how your software works. Let's describe these changes in more detail in the following sections.
A patch change means we increment the right most digit by one. Changing the said software from 1.0.0 to 1.0.1 is a small change, usually a bug fix. As a user of that software you don't really have to worry; if anything, you should be happy that something is suddenly working better. The point is, you can safely start using 1.0.1.
This means the software is increased from 1.0.0 to 1.1.0. We are dealing with a more severe change as we increase the middle digit by one. This number should be increased when functionality is added to the software and it should still be backwards compatible. Also in this case it should be safe adapting the 1.1.0 version of the software.
At this stage, the version number increases from 1.0.0 to 2.0.0. Now this is where you need to look out. At this stage, things might have changed so much that constructs have been renamed or removed. It might not be compatible to earlier versions. I'm saying it might because a lot of software authors still ensure that there is a decent backwards compatibility, but the main point here is that there is no warranty, no contract, guaranteeing that it will still work.
The first version of Angular was known by most people as Angular 1; it later became known as AngularJS. It did not use semantic versioning. Most people actually still refer to it as Angular 1.
Then Angular came along and in 2016 it reached production readiness. Angular decided to adopt semantic versioning and this caused a bit of confusion in the developer community, especially when it was announced that there would be an Angular 4 and 5, and so on. Google, as well as the Google Developer Experts, started to explain to people that it wanted people to call the latest version of the framework Angular - just Angular. You can always argue on the wisdom of that decision, but the fact remains, the new Angular is using semantic versioning. This means Angular is the same platform as Angular 4, as well as Angular 11, and so on, if that ever comes out. Adopting semantic versioning means that you as a user of Angular can rely on things working the same way until Google decides to increase the major version. Even then it's up to you if you want to remain on the latest major version or want to upgrade your existing apps.
As mentioned before, Angular represents a full rewrite of the AngularJS framework, introducing a brand new application architecture completely built from scratch in TypeScript, a strict superset of JavaScript that adds optional static typing and support for interfaces and decorators.
In a nutshell, Angular applications are based on an architecture design that comprises of trees of web components interconnected by their own particular I/O interface. Each component takes advantage under the covers of a completely revamped dependency injection mechanism.
To be fair, this is a simplistic description of what Angular really is. However, the simplest project ever made in Angular is cut out by these definition traits. We will focus on learning how to build interoperable components and manage dependency injection in the next chapters, before moving on to routing, web forms, and HTTP communication. This also explains why we will not make explicit references to AngularJS throughout the book. Obviously, it makes no sense to waste time and pages referring to something that will not provide any useful insights on the topic, besides the fact we assume that you might not know about Angular 1.x, so such knowledge does not have any value here.
Web components is a concept that encompasses four technologies designed to be used together to build feature elements with a higher level of visual expressivity and reusability, thereby leading to a more modular, consistent, and maintainable web. These four technologies are as follows:
Templates
: These are pieces of HTML that structure the content we aim to render
Custom elements
: These templates not only contain traditional HTML elements, but also the custom wrapper items that provide further presentation elements or API functionalities
Shadow DOM
: This provides a sandbox to encapsulate the CSS layout rules and JavaScript behaviors of each custom element
HTML imports
: HTML is no longer constrained to host HTML elements, but to other HTML documents as well
In theory, an Angular component is indeed a custom element that contains a template to host the HTML structure of its layout, the latter being governed by a scoped CSS style sheet encapsulated within a shadow DOM container. Let's try to rephrase this in plain English. Think of the range input control type in HTML5. It is a handy way to give our users a convenient input control for entering a value ranging between two predefined boundaries. If you have not used it before, insert the following piece of markup in a blank HTML template and load it in your browser:
<input id="mySlider" type="range" min="0" max="100" step="10">
You will see a nice input control featuring a horizontal slider in your browser. Inspecting such control with the browser developer tools will unveil a concealed set of HTML tags that were not present at the time you edited your HTML template. There you have an example of shadow DOM in action, with an actual HTML template governed by its own encapsulated CSS with advanced dragging functionality. You will probably agree that it would be cool to do that yourself. Well, the good news is that Angular gives you the toolset required for delivering this very same functionality, so we can build our own custom elements (input controls, personalized tags, and self-contained widgets) featuring the inner HTML markup of our choice and our very own style sheet that does not affect (nor is impacted) by the CSS of the page hosting our component.
Angular applications can be coded in a wide variety of languages and syntaxes: ECMAScript 5, Dart, ECMAScript 6, TypeScript, or ECMAScript 7.
TypeScript is a typed superset of ECMAScript 6 (also known as ECMAScript 2015) that compiles to plain JavaScript and is widely supported by modern OSes. It features a sound object-oriented design and supports annotations, decorators, and type checking.
The reason why we picked (and obviously recommend) TypeScript as the syntax of choice for instructing how to develop Angular applications in this book is based on the fact that Angular itself is written in this language. Being proficient in TypeScript will give the developer an enormous advantage when it comes to understanding the guts of the framework.
On the other hand, it is worth remarking that TypeScript's support for annotations and type introspection turns out to be paramount when it comes to managing dependency injection and type binding between components with a minimum code footprint, as we will see further down the line in this book.
Ultimately, you can carry out your Angular projects in plain ECMAScript 6 syntax if that is your preference. Even the examples provided in this book can be easily ported to ES6 by removing type annotations and interfaces, or replacing the way dependency injection is handled in TypeScript with the most verbose ES6 way.
For the sake of brevity, we will only cover examples written in TypeScript and actually recommend its use because of its higher expressivity thanks to type annotations, and its neat way of approaching dependency injection based on type introspection out of such type annotations.
There are different ways to get started, either using the Angular quickstart repository on the https://angular.io/ site, or installing the scaffolding tool Angular CLI, or lastly, you could use Webpack to set up your project. It is worth pointing out that the standard way of creating a new Angular project is through using Angular CLI and scaffold your project. Systemjs, used by the quickstart repository, is something that used to be the default way of building Angular projects. It is now rapidly diminishing, but it is still a valid way of setting up an Angular project. The interested reader is therefore recommended to check the Appendix A, SystemJS for more information on it.
Setting up a frontend project today is more cumbersome than ever. We used to just include the necessary script with our JavaScript code and a link tag for our CSS and img tag for our assets and so on. Life used to be simple. Then frontend development became more ambitious and we started splitting up our code in modules, we started using preprocessors for both our code and CSS. All in all, our projects became more complicated and we started to rely on build systems such as Grunt, Gulp, Webpack, and so on. Most developers out there are not huge fans of configuration, they just want to focus on building apps. Modern browsers, however, do more to support the latest ECMAScript standard and some browsers have even started to support modules, which are resolved at runtime. This is far from being widely supported though. In the meantime, we still have to rely on tools for bundling and module support.
Setting up a project with leading frameworks such as React or Angular can be quite difficult. You need to know what libraries to import and ensure that files are processed in the correct order, which leads us into the topic of scaffolding tools. For AngularJS, it was quite popular to use Yeoman to scaffold up a new application quickly and get a lot of nice things preconfigured. React has a scaffolder tool called create-react-app, which you probably have saved and it saves countless hours for React developers. Scaffolder tools becomes almost a necessity as complexity grows, but also where every hour counts towards producing business value rather than fighting configuration problems.
The main motivation behind creating the Angular CLI tool was to help developers focus on app building and not so much on configuration. Essentially, with a simple command, you should be able to scaffold an application, add a new construct to it, run tests, or create a production grade bundle. Angular CLI supports all that.
What you need to get started is to have Git and Node.js installed. Node.js will also install something called NPM, a node package manager that you will use later to install files you need for your project. After this is done, you are ready to set up your Angular application. You can find installation files to Node.js at https://nodejs.org.
The easiest way to have it installed is to go to the site:
https://nodejs.org/en/download/
Installing Node.js will also install something called NPM, Node Package Manager, which you will need to install dependencies and more. The Angular CLI requires Node 6.9.0 and NPM 3 or higher. Currently on the site, you can choose between an LTS version and the current version. The LTS version should be enough.
Installing the Angular CLI is as easy as running the following command in your Terminal:
npm install -g @angular/cli
On some systems, you may need to have elevated permissions to do so; in that case, run your Terminal window as an administrator and on Linux/macOS instead run the command like this:
sudo npm install -g @angular/cli
Once the Angular CLI is in place the time has come to create your first project. To do so place yourself in a directory of your choice and type the following:
ng new <give it a name here>
Type the following:
ng new TodoApp
This will create a directory called TodoApp. After you have run the preceding command, there are two things you need to do to see your app in a browser:
Navigate to the just created directory
Serve up the application
This will be accomplished by the following commands:
cd TodoApp
npm start
At this point, open up your browser on http://localhost:4200 and you should see the following:
The Angular CLI doesn't just come with code that makes your app work. It also comes with code that sets up testing and includes a test. Running the said test is as easy as typing the following in the Terminal:
npm test
You should see the following:
How come this works? Let's have a look at the package.json file that was just created and the scripts tag. Everything specified here can be run using the following syntax:
npm run <key>
In some cases, it is not necessary to type run and it will be enough to just type:
npm <key>
This is the case with the start and test commands.
The following listing makes it clear that it is possible to run more commands than start and test that we just learned about:
"scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e"}
So far we have learned how to install the Angular CLI. Using the Angular CLI we have learned to:
Scaffold a new project.
Serve up the project and see it displayed in a browser.
Run tests.
That is quite an accomplishment. We will revisit the Angular CLI in a later chapter as it is a very competent tool, capable of a lot more.
We are about to take the first trembling steps into building our first component. The Angular CLI has already scaffolded our project and thereby carried out a lot of heavy lifting. All we need to do is to create new file and starting filling it with content. The million dollar question is what to type?
So let's venture into building our first component. There are three steps you need to take in creating a component. Those are:
Import the component decorator construct.
Decorate a class with a component decorator.
Add a component to its module ( this might be in two different places).
A selector is what it should be referred to if used in a template somewhere else. As we call it app, we would refer to it as:
<app></app>
The template or templateUrl is your view. Here you can write HTML markup. Using the template keyword, in our object literal, means we get to define the HTML markup in the same file as the component class. Were we to use templateUrl, we would then place our HTML markup in a separate file.
The preceding example also lists the following double curly braces, in the markup:
<h1>
{{ title }}
</h1>
This will be treated as an interpolation and the expression will be replaced with the value of AppComponent's title field. The component, when rendered, will therefore look like this:
hello app
Now we need to introduce a completely new concept, an Angular module. All types of constructs that you create in Angular should be registered with a module. An Angular module serves as a facade to the outside world and it is nothing more than a class that is decorated by the decorate @NgModule. Just like the @Component decorator, the @NgModule decorator takes an object literal as an input parameter. To register our component with our Angular module, we need to give the object literal the property declarations. The declarations property is of a type array and by adding our component to that array we are registering it with the Angular module.
The following code shows the creation of an Angular module and the component being registered with it by being added to declarations keyword array:
import { AppComponent } from './app.component';@NgModule({
declarations: [AppComponent]
})export class AppModule {}
At this point, our Angular module knows about the component. We need to add one more property to our module, bootstrap. The bootstrap keyword states that whatever is placed in here serves as the entry component for the entire application. Because we only have one component, so far, it makes sense to register our component with this bootstrap keyword:
@NgModule({ declarations: [AppComponent],
bootstrap: [AppComponent]
})export class AppModule {}
It's definitely possible to have more than one entry component, but the usual scenario is that there is only one.
For any future components, however, we will only need to add them to the declarations property, to ensure the module knows about them.
So far we have created a component and an Angular module and registered the component with said the module. We don't really have a working application yet, as there is one more step we need to take. We need to set up the bootstrapping.
The main.ts file is your bootstrap file and it should have the following content:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';import { AppModule } from './app/app.module';platformBrowserDynamic()
.bootstrapModule(AppModule);
What we do in the preceding code snippet is to provide the recently created module as an input parameter to the method call bootstrapModule(). This will effectively make the said module, the entry module of the application. This is all we need to create a working application. Let's summarize the steps we took to accomplish that:
Create a component.
Create a module and register our created component in its declaration property.
Also register our component in the modules bootstrap property to make it serve as an application entry point. Future components we create just need to be added to the
declarations
property.
Bootstrap our created module by using the said module as an input parameter to the
bootstrapModule()
method.
You as a reader have had to swallow a lot of information at this point and take our word for it. Don't worry, you will get a chance to get more acquainted with components in this chapter as well as Angular modules in upcoming chapters. For now, the focus was just to get you up and running by giving you a powerful tool in the form of the Angular CLI and show you how few steps are actually needed to have an app rendered to the screen.
We have come a long way now, from tapping on TypeScript for the first time to learning how to code the basic scripting schema of an Angular component. However, before jumping into more abstract topics, let's try to build another component so we really get the hang of how creating it really works.