45,59 €
Learn everything you need to build highly scalable, robust web applications using Angular release 4
This book is for JavaScript developers with some prior exposure to Angular, at least through basic examples. We assume that you've got working knowledge of HTML, CSS, and JavaScript.
Got some experience of Angular under your belt? Want to learn everything about using advanced features for developing websites? This book is everything you need for the deep understanding of Angular that will set you apart from the developer crowd.
Angular has introduced a new way to build applications. Creating complex and rich web applications, with a lighter resource footprint, has never been easier or faster. Angular is now at release 4, with significant changes through previous versions.
This book has been written and tested for Angular release 4.
Angular is a mature technology, and you'll likely have applications built with earlier versions. This book starts by showing you best practices and approaches to migrating your existing Angular applications so that you can be immediately up-to-date. You will take an in-depth look at components and see how to control the user journey in your applications by implementing routing and navigation. You will learn how to work with asynchronous programming by using Observables.
To easily build applications that look great, you will learn all about template syntax and how to beautify applications with Material Design. Mastering forms and data binding will further speed up your application development time. Learning about managing services and animations will help you to progressively enhance your applications. Next you'll use native directives to integrate Bootstrap with Angular. You will see the best ways to test your application with the leading options such as Jasmine and Protractor.
At the end of the book, you'll learn how to apply design patterns in Angular, and see the benefits they will bring to your development.
This book provides comprehensive coverage of all aspects of development with Angular. You will learn about all the most powerful Angular concepts, with examples and best practices. This book is everything you need for the deep understanding of Angular that will set you apart from the developer crowd.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 417
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
< html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
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: July 2017
Production reference: 1310717
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78588-023-0
www.packtpub.com
Authors
Mathieu Nayrolles
Rajesh Gunasundaram
Sridhar Rao
Copy Editor
Dhanya Baburaj
Reviewers
Andrea Chiarelli
Phodal Huang
Project Coordinator
Devanshi Doshi
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Larissa Pinto
Indexer
Mariammal Chettiyar
Content Development Editor
Aditi Gour
Graphics
Jason Monteiro
Technical Editor
Akansha Bathija
Production Coordinator
Shantanu Zagade
Mathieu Nayrolles was born in France and lived in a small village in Cote d'Azur for almost 15 years. He started his computer science studies in France and continued them in Montreal, Canada, where he now lives with his wife. Mathieu holds master's degrees from eXia.Cesi (Software Engineering) and UQAM (Computer Science) and he is now a PhD student at Concordia University (Electrical and Computer Engineering), Montreal, Canada, under the supervision of Dr. Wahab Hamou-Lhadj.
Despite his academic journey, Mathieu also worked for worldwide companies such as Airbus, Saint-Gobain, Ericsson, and Ubisoft, where he learned how important good technical resources are.
Mathieu worked start working with AngularJS in 2011 and moved over Angular2 when the rc1 came out. During these 6 years, he acted as an Angular coach, mentor, and consultant for various companies in Canada, USA, and France. He also gives classes on Angular to software engineering students and professionals in Montreal, Canada.
Finally, Mathieu is the co-founder and CTO of toolwatch.io (a website and companion mobile apps that allow you to measure the precision of your mechanical watches), where he uses Angular daily.
You can discover some of his works through his other books: Xamarin Studio for Android Programming: A C# Cookbook, Mastering Apache Solr: A practical guide to get to grips with Apache Solr,Instant Magento Performances, and Instant Magento Performance Optimization How-to, published by Packt.
Follow @MathieuNls on Twitter for even more information.
Rajesh Gunasundaram is a software architect, technical writer and blogger. He has over 15 years of experience in the IT industry, with more than 12 years using Microsoft .NET, 2 years of BizTalk Server and a year of iOS application development.
Rajesh is a founder and editor of technical blogs programmerguide.net and ioscorner.com and you can find many of his technical writings on .Net and iOS. He is also the founder and developer of VideoLens.co, a platform that analyses videos uploaded in Facebook pages and YouTube channels. Rajesh has also written other books for Packt publishing like Learning Angular for .Net Developers,ASP.NET Web API Security Essentials, and CORS Essentials.
Rajesh is also an YouTuber running channel ProgrammerGuide. Rajesh holds a master
degree in Computer Application and began his career as a software engineer in the year 2002. He worked on client premises located at various countries such as UK, Belarus and Norway. He also has experience in developing mobile applications for iPhone and iPad.
His technical strengths include Azure, Xamarin, ASP.NET MVC, Web API, WCF, .Net Framework / .Net Core, C#, Objective-C, Angular, Bot Framework, BizTalk, SQL Server, REST, SOA, Design Patterns and Software Architecture.
Rajesh is an early adopter of Angular since AngularJS. He has developed Rich interfaces using Angular, Bootstrap, HTML5 and CSS3. He has good experience in translation of designer mock-ups and wireframes into an AngularJS front-end. Good at unit testing Angular applications with Karma. Expertise in handling RESTful services in Angular. Supporting various web products developed using AngularJS and Angular.
Sridhar Rao holds Bachelor of Engineering degree in Information Technology from SGGS Nanded. Sridhar currently works as a Technical Lead at a leading MNC, where he is part of digital practice. Sridhar has over 10 years of experience primarily focused on frontend engineering. He has previously worked with Oracle India, Cognizant Technology Solutions, and Tech Mahindra.
To his credit, Sridhar has also led large teams implementing complex applications using AngularJS for a leading investment bank. He has successfully designed and developed reporting and dashboard application using hybrid AngularJS and Angular frameworks for a leading freight shipping company and a leading low-cost airline.
Sridhar has been a senior developer involved in migrating an entire business-critical application from AngularJS to Angular for a leading media giant.
He is author of the book PHP and script.aculo.us Web 2.0 Application Interfaces, published by Packt.
Sridhar is based in New York City, USA. His hobbies include playing the keyboard and traveling.
Andrea Chiarelli has more than 20 years of experience as a software engineer and technical writer. In his professional career, he has used various technologies for the projects he has been involved in, from C# to JavaScript, from Angular to React, from ASP.NET to PhoneGap/Cordova.
He has contributed to many online and offline magazines and has been the author of a few books published by Wrox Press. His latest book, Mastering JavaScript OOP, was published by Packt Publishing.
Currently, he is a senior software engineer at the Italian office of Apparound Inc. and a regular contributor to HTML.it, an Italian online magazine focused on web technologies.
Phodal Huang is a developer, creator, and an author. He currently works for ThoughtWorks as a consultant. He now focuses on IoT and frontend development. He is the author of Design Internet of Things and Growth: Thinking in Full Stack (in publishing) in Chinese.
He is an open source enthusiast and has created a series of projects in GitHub. After a day's work, he likes to reinvent some wheels for fun. He created the application Growth with Ionic 2 and Angular 2, which is about coaching newbies how to learn programming, and rewriting with React Native.He loves designing, writing, hacking, and traveling.
He has worked on books such as Learning IoT, Smart IoT Projects, Angular Services, and Getting Started with Angular.
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/1785880233.
If you'd like to join our team of regular reviewers, you can e-mail 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
Architectural Overview and Building a Simple App in Angular
Angular architecture
NgModules
Components
Templates
Metadata
Data Binding
Directives
Services
Dependency Injection
Basics of TypeScript
Basic types
Number type
Boolean type
String
Array
Enum
Any
Void
Classes
Interfaces
Optional properties using an interface
Function type interfaces
Array type interfaces
Class type interfaces
Extending interfaces
Hybrid type interfaces
Inheritance
Inheritance in TypeScript
Private and public modifiers
Accessors
Static properties
Modules
Namespaces
Modules
Functions
Optional and default parameters
Rest parameter
Generics
Generic interfaces
Generic classes
Decorators
Class decorators
Method decorators
Accessor decorators
Property decorators
Parameter decorators
Building a simple application
Summary
Migrating AngularJS App to Angular App
Migration process
Syntax difference between Angular and AngularJS
Local variables and bindings in templates
Filters and pipes in templates
Local variables in templates
Angular app directives
Handling the CSS classes
Binding click event
Controllers and components in templates
Benefits of upgrading to Angular
Strategies to upgrade to Angular
Rules for incremental upgrade to Angular
Incremental upgrading using UpgradeAdapter
Injecting AngularJS dependencies to Angular
Injecting Angular dependencies to AngularJS
Components migration
Roadmap from AngularJS to Angular
JavaScript to TypeScript
Installing Angular packages
Creating the AppModule
Bootstrapping your application
Upgrading application services
Upgrading your application component
Adding the Angular router
Summary
Using Angular CLI to Generate Angular Apps with Best Practices
Introducing Angular CLI
Installing and setting up Angular CLI
Generating code for a new application
Generating components and routes
Routes
Generating services
Generating directives and pipes
Pipes
Creating builds targeting various environments
Running tests for your application
Updating Angular CLI
Summary
Working with Components
Components 101
A basic root component
Defining child components
Component life cycle
Communicating and sharing data between components
Referencing child components from a parent component
Template reference variables
Injecting child components
Using services with components
Summary
Implementing Angular Routing and Navigation
Importing and configuring the router
Building blocks of router
About router LocationStrategy
Handling the error state - wildcard route
Route Guards
Custom component routes and child routes
Custom component routes with inner child routes
Integrating all the components together
Demo application routing and navigation
Summary
Creating Directives and Implementing Change Detection
Angular Directives
Component Directives
Structural Directives
ngFor directive
ngIf directive
ngSwitch directive
Attribute Directives
Built-in Attribute Directives
Creating custom directives - Structural and Attribute Directives
Angular CLI - generating the directives
Creating custom Attribute Directives
Creating custom Structural Directives
Implementing change detection in Angular
Change detection - Angular and ZoneJS
Change detection strategy
ChangeDetectionStrategy - Default
ChangeDetectionStrategy - OnPush
Advantages of ChangeDetectionStrategy - OnPush
Summary
Asynchronous Programming Using Observables
Observer patterns
TypeScript Observable
TypeScript Observable with parameters
Observing HTTP responses
Implementation
Understanding the implementation
Promises
Summary
Template and Data Binding Syntax
Learning about Template Syntax
Various ways to include Template Syntax
Using inline Template Syntax
Using templateURL to include a template
Interpolation in templates
Template expressions in Angular
Attaching events to views in templates
Implementing directives inside templates
Bindings in the template
Angular Data Binding
One-way Data Binding - Data source to view
One-way Data Binding - View template to data source
Angular Two-way Data Binding
Summary
Advanced Forms in Angular
Getting started
Reactive forms
Using FormBuilder
Adding validations
Custom validation
Two-way Data Binding with ngModel
Keeping things neat (extra credit)
Summary
Material Design in Angular
Installing the package
Responsive layout
Material icons
Buttons
Menu
Toolbars
Dialogs
Side navigation drawers
Theming
Summary
Implementing Angular Pipes
Angular Pipes - An overview
Defining a pipe
Built-in Pipes
DatePipe
DecimalPipe
CurrencyPipe
LowerCasePipe and UpperCasePipe
JSON Pipe
SlicePipe
async Pipe
Parameterizing pipes
Chaining pipes
Creating custom pipes
Pure and Impure Pipes
Pure Pipes
Impure Pipes
Summary
Implementing Angular Services
Why use a service or factory?
Creating a service
Accessing data from components using services
Implementing services
Consuming the service
Creating an asynchronous service
What is a Promise?
Using a Promise in a service
Summary
Applying Dependency Injection
Applications without Dependency Injection
Dependency Injection - Introduction
Understanding provider classes
Understanding hierarchical DI
Overview - Hierarchical components and DI
Creating an injectable
Registering providers
Registering providers inside the component
Provider classes with dependencies
Using @Inject, provide, and useValue
Summary
Handling Angular Animation
Introduction to Angular animations
Installing the Angular animations library
Angular animation - Specific functions
Trigger
States
Transitions
Animating page transitions
One more example - Angular animations
Using keyframes - Sequence of styles
Animate collapse menu
Summary
Integrating Bootstrap with Angular Application
Installing Bootstrap
Understanding the grid system
Using Bootstrap directives
Accordion
Alert
Datepicker
Tooltip
Progress bar
Rating
Summary
Testing Angular Apps Using Jasmine and Protractor Frameworks
Concepts in testing
Understanding and setting up Angular CLI for testing
Introduction to Jasmine framework
The Jasmine framework - Global methods we can use
Commonly used methods in Jasmine
Angular CLI and Jasmine framework - First test
Testing Angular components with Jasmine
Testing Angular components with Jasmine
Testing Angular components - Advanced
TestBed
Example - Writing test scripts with change detection
Testing Angular services
Testing Angular services - Mocking backend services
Introduction to Protractor framework
Protractor - A quick overview
Protractor and DOM
Some methods available to select element(s)
Exploring the Protractor API
Protractor - First steps
Writing E2E tests using Protractor
Writing E2E tests using Protractor - Advanced
Summary
Design Patterns in Angular
Model-View-Controller (MVC)
MVC at large
MVC limitations for the frontend
Angular is MVC
Singleton and Dependency Injection
Prototype and reusable pool
Factory pattern
Memento pattern
Summary
Learn how to build great applications with the Angular framework for any deployment target--be it mobile, desktop, or native apps.
The book covers everything that is required to write modern, intuitive, and responsive applications.
The book covers concepts and fundamentals along with detailed code snippets and examples that will help you jump-start and open up new ideas by learning the Angular framework.
The chapters in the book cover topics that will help any developer pick up Angular programming skills easily. At the same time, experienced and seasoned developers will learn master the skillset of migrating from the existing AngularJS framework and also learn advanced techniques and best practices covered throughout the book.
Along with great functionality, any application heavily relies on design aspects as well. The book will introduce you to and help you sharpen your design skills with Material Design and Bootstrap CSS.
Learn how to write and create reusable, testable, and maintainable services, forms, pipes, async programming, animations, routing, and much more.
Did we say testable? You bet. The book introduces you to Jasmine and the Protractor framework. While learning about the frameworks, we will learn to write unit test scripts using Jasmine and also end-to-end test scripts using the Protractor framework.
The journey of learning and mastering Angular skills will be fun, thought-provoking, and above all easy. Step-by-step guides helps users to implement the concepts in your applications and projects.
Chapter 1, Architectural Overview and Building a Simple App in Angular, explains Angular architecture, the basics of TypeScript, and also how to create a simple Angular application.
Chapter 2, Migrating AngularJS App to Angular App, shows how to migrate an AngularJS application to Angular 4, and we will also discuss best practices in migrating the application.
Chapter 3, Using Angular CLI to Generate Angular Apps with Best Practices, shows how to use Angular command-line interface to generate boilerplate code for an Angular application.
Chapter 4, Working with Components, discusses the life cycle of components. We will learn how to implement multiple and container components and also the interactions between different components.
Chapter 5, Implementing Angular Routing and Navigation, shows how to create routing strategies and routes for our Angular applications. We will learn the building blocks of routing, create routes, child routes, and secure routes using route guards. States are an important aspect in routing. We will implement states to make secure, multi-state application routes.
Chapter 6, Creating Directives and Implementing Change Detection, explains directives, different types of directive provided by Angular, and also how to create custom user-defined directives. We will deep dive into learning how Angular handles change detection and how we can utilize change detection in our apps.
Chapter 7, Asynchronous Programming Using Observables, shows how to take advantage of asynchronous programming with Angular by using Observable and Promises. In addition, we learn how to built a basic yet extensible asynchronous JSON API for querying the Marvel cinematic universe.
Chapter 8, Template and Data Binding Syntax, discusses the template syntax for writing expressions, operators, attributes, and attaching events to elements. Data binding is one of the key features that allows data mapping from data source to view target and vice versa. Additionally, we will also learn different ways of data binding and create lot of examples along.
Chapter 9, Advanced Forms in Angular, explains how to use and master reactive forms. We tackle the reactive part of reactive forms by emphasizing the relationship between your HTML models and your NgModels so every change on a given form is propagated to the model.
Chapter 10, Material Design in Angular, discusses Material Design, which is a new hype regarding design. In this chapter, we learn how to integrate material design with Angular. In addition, we learn how to use useful components such as grid and button.
Chapter 11, Implementing Angular Pipes, explain that transforming data in the views is one of the most common rituals we have to do it in our applications. We will learn how to transform values using various built-in pipes and create our own pipes. Additionally, we will learn how to pass parameters and customize pipes based on our needs.
Chapter 12, Implementing Angular Services, discusses services and factories, creating Angular services, accessing data from components using services, and creating asynchronous services.
Chapter 13, Applying Dependency Injection, explains how to create injectables, services, and provider classes that can be used as shared resources between various components. Additionally, we will learn how to create and use the objects created dynamically just-in-time using Inject, Provider, useClass, and useValue.
Chapter 14, Handling Angular Animation, show that animations are key to designing and building beautiful user experiences with smooth transitions and effects. We will learn and implement examples using animations, transitions, states, and keyframes.
Chapter 15, Integrating Bootstrap with Angular Application, discusses Bootstrap, which is arguably the most popular frontend framework out there and, in this chapter, we learn what it means to have an Angular x Bootstrap application.
Chapter 16, Testing Angular Apps Using the Jasmine and Protractor Frameworks, teaches the use of arguably the most important aspect of the software development process - testing Angular applications using the Jasmine and Protractor frameworks. We will start with an overview of each of the frameworks and then move on to the testing utilities provided by Angular. We will also create sample test scripts for testing Angular components and services.
Chapter 17, Design Patterns in Angular, discusses Typescript, is object-oriented programming language with which, we can leverage decades of knowledge on object-oriented architecture. In this chapter, we explore some of the most useful object-oriented design patterns and learn how to apply them in an Angular way.
You will need the following list of softwares:
NodeJS 6.10 or latest version
NPM 3.10 or later
Good editor such as Visual Studio Code or Sublime Text
Browser such as chrome or firefox or edge
Internet connection to download and install node packages
This book is for JavaScript developers with some prior exposure to Angular. We assume that you ve got a working knowledge of HTML, CSS, and JavaScript.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Then, we go into the advanced-forms folder and prune everything that is not inside the chap7/angular-promise subdirectory."
A block of code is set as follows:
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })
Any command-line input or output is written as follows:
npm install -g typescript
tsc mytypescriptcodefile.ts
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
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 e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for 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/Expert-Angular. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ExpertAngular_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.
It doesn't matter if you are new to AngularJS or new to Angular. If you want to quickly develop great web apps with rich UIs and with the features of Angular components, templates, and services, you need to master Angular, and this book is for you.
Angular is a JavaScript framework that enables developers to build web and mobile applications. Applications built with Angular can target any device, such as mobiles, tablets, and desktops. Angular is not an incremental version of AngularJS. It was completely rewritten with improved Dependency Injection, dynamic loading, and simpler routing, and recommends that developers use TypeScript and leverage OOPS, static typing, generics, and lambdas.
In this chapter, we will cover the following topics:
Angular architecture
Basics of TypeScript
Building a simple application
Before we discuss architecture, let's see what's new in Angular. The primary focus of Angular is mobiles, as it is important to consider the performance and loading time of the application on a mobile phone. Many modules are decoupled from the Angular core, leaving only the modules that are definitely core; removing unwanted modules from Angular core leads to better performance.
Angular targets ES6 and leverages TypeScript as a development script language that enables compile time checks for types, rather than at runtime. TypeScript provides additional information about classes when instantiating them by annotating metadata to the classes. You can also use ES5 and Dart as the development language. There is an improved version of Dependency Injection that supports child injectors and instance scope. Router was rewritten completely and the component router was introduced. The Component Directive, the Decorator Directive, and the Template Directive are supported in Angular. The $scope has been completely removed from Angular.
The architecture of Angular comprises Modules, Components, Templates, Metadata, Directives, and Services:
Angular framework has various libraries that are grouped as modules in order to build an application. Angular applications are modular in nature and are constructed by assembling various modules. Modules may have components, services, functions, and/or values. Some modules may have a collection of other modules and are known as library modules.
Angular packages, such as core, common, http, and router that are prefixed with @angular comprise many modules. We import what our application needs from these library modules as follows:
import {Http, Response} from @angular/http';
Here, we import Http and Response from the library module, @angular/http. @angular/http refers to a folder in the Angular package. Any module defined to be exported can be imported into another module by referring to the filename of the module.
However, we can also refer to the folder as we referred to @angular/http. This can be achieved by adding an index.ts file to the folder and adding the code to export modules from the folder. This is a best practice suggested by Angular's style guide and is called the barrel technique:
export * from './http';
This is the export statement in the index.ts found in @angular/http. The statement means that it exports all the modules in HTTP and that they can be imported to our application wherever needed.
When we write an Angular application, we start by defining an AppComponent (not necessarily with the same name) and exporting it.
Templates can be thought of as a representation of a component that is visualized according to the UI/UX needs of an application. A component will have a template associated with it. The template is responsible for displaying and updating data according to user events:
Here is a simple template that displays the title and author of a book:
<h1>Book Details</h1> <p>Title of the Book: {{title}}</p> <p>Author Name : {{author}}</p>
Here, the title and author values wrapped in curly braces will be supplied by the associated component instance.
We will discuss templates and their syntax in detail in Chapter 8, Template and Data Binding Syntax.
A class can be turned into a component by annotating it with @Component and passing the necessary metadata, such as selector, template, or templateUrl. Angular considers a class as a component only after attaching metadata to it:
Let's revisit the BookComponent class we defined earlier. Angular does not consider this class as a component unless we annotate it. TypeScript leverages the ES7 feature by providing a way to decorate a class with metadata as follows:
@Component({ selector: 'book-detail', templateUrl: 'app/book.component.html' }) export class BookComponent { ... }
Here, we have decorated the BookComponent class with @Component and attached metadata selector and templateUrl. It means that, wherever Angular sees the special <book-detail/> tag in the view, it will create an instance of BookComponent and render the view assigned to templateUrl, which is book.component.html.
A decorator provided by TypeScript is a function that takes configuration parameters that are used by Angular to create an instance of the component and render the associated view. Configuration parameters may also have information about directives and providers, which will be made available by Angular when the component is created.
Data Binding is one of the core responsibilities of developers when writing code to bind data to the user interface and update changing data according to user interactions with the user interface. Angular has reduced the burden of writing large amounts of code to handle Data Binding:
Angular handles Data Binding by coordinating with templates and components. The templates provide instructions to Angular on how and what to bind. There are two types of binding in Angular: globally One-way Data Binding and Two-way Data Binding. One-way Data Binding deals with either binding data from the component to the DOM or from the DOM to the component. Two-way Data Binding deals with both sides of communication, that is, the component to the DOM and the DOM to the component.
<div>Title: {{book.title}}<br/> Enter Author Name: <input [(ngModel)]="book.author"> </div>
Here, book.title wrapped in double curly braces deals with One-way Data Binding. The value of book title, if available in the component instance, will be displayed in the view. book.author, assigned to the ngModel property of the input element, deals with Two-way Data Binding. If the component instance has a value in the author property, then it will be assigned to the input elements, and if the value is changed by the user in the input control, then the updated value will be available in the component instance.
We will learn in detail about Data Binding in Chapter 8, Template and Data Binding Syntax.
Services are user-defined classes used to solve problems. Angular recommends only having template-specific codes in components. A component's responsibility is to enrich the UI/UX in the Angular application and delegate business logic to services. Components are consumers of services:
Application-specific or business logic such as persisting application data, logging errors, and file storage should be delegated to services, and components should consume the respective services to deal with the appropriate business or application-specific logic:
For example, we can have a service called BookService that deals with inserting new books, editing or deleting existing books, and fetching a list of all the books available.
We will see more about services in Chapter 11, Implementing Angular Pipes.
When an instance of a class is created, supplying the required dependencies of that class for it to function properly is called Dependency Injection. Angular provides a modern and improved version of Dependency Injection:
In Angular, the injector maintains the containers to hold the instances of the dependencies and serves them as and when required. If the instance of a dependency is not available in the container, then the injector creates an instance of the dependency and serves it:
As stated earlier, components have logic that is related to templates and mostly consume services to perform business logic. So, components depend on services. When we write code for components, we create a parameter constructor that takes the service as an argument. It means that creating an instance of the component depends on the service parameter in the constructor. Angular requests that the injector provide the instance of the service in the parameter of the constructor of the component. The injector will serve the instance of the requested service, if available; otherwise, it creates a new one and serves it:
export class BookComponent { constructor(private service: BookService) { } }
In this code snippet, the : symbol comes from TypeScript and is not Angular syntactical sugar. The private keyword is also from TypeScript and enables assigning the passed constructor to the class instance automatically. The type information is used to infer the type to be injected. The BookComponent has a dependency to BookService and is injected in the constructor. So when an instance of the BookComponent is created, Angular will also make sure the instance of BookService is readily available for the BookComponent instance to consume.
The injector has knowledge of the dependencies to be created from providers that are configured with the required dependency types when bootstrapping the application or when decorating the components, as follows:
@NgModule({ imports: [BrowserModule], declarations: [AppComponent,], providers: [BookService], bootstrap: [ AppComponent ] }) export class AppModule { }
The preceding code snippet adds BookService as a provider to the bootstrap function. The injector will create an instance of BookService and keep it available in the container for the entire application to inject whenever it's requested:
@Component({ providers: [BookService] }) export class BookComponent { ... }
The preceding code snippet adds BookService as a provider in the metadata of the component. The injector will create an instance of BookService when it encounters a request to create an instance of BookComponent.
We will discuss Dependency Injection and hierarchical Dependency Injection in detail in Chapter 12, Implementing Angular Services.
TypeScript is a superset of JavaScript and is an open source language developed by Microsoft. Code written in TypeScript will be compiled to JavaScript and executed on any browser or server running Node.js. TypeScript is actually a type of JavaScript. TypeScript helps to improve the quality of code you write in JavaScript. If we use external libraries, we need to use type definition files for the imported libraries. Type definition files provide JavaScript tooling support and also enable compile time checks, code refactoring, and variable renaming support by inferring the structure of the code. TypeScript is evolving and keeps adding additional features aligned with the ES2016 specification and later.
There are various editors available on the market that write TypeScript code and compile them using a TypeScript compiler. These editors take care of compiling your TypeScript into JavaScript. Some popular editors are shown here:
Visual Studio
Visual Studio Code
Sublime text
Atom
Eclipse
Emacs
WebStorm
Vim
You can also download TypeScript as a Node.js package by executing the following command in the Node.js command-line tool to install TypeScript globally:
npm install -g typescript
To transpile the TypeScript code into JavaScript, you can execute the following command in the command-line tool:
tsc mytypescriptcodefile.ts
Here, tsc is the TypeScript compiler that converts a TypeScript file into a JavaScript file. mytypescriptfile is the name of your TypeScript code file and .ts is the extension of the TypeScript file. On executing the tsc command, it generates a .js file with the same name as the .ts source file.
We will be using Visual Studio Code editor for our sample code demos in this chapter. Let us see basic features of TypeScript with examples.
Let's explore some of the basic types in TypeScript and how to use them. Basic types include primitive types such as number, string, boolean, and array in TypeScript. JavaScript only validates types during runtime, but TypeScript validates variable types during compile time and greatly reduces the possibility of typecast issues during runtime.
Void is actually nothing. It can be used as the return type of a function to declare that this function will not return any value:
function alertMessage(): void { alert("This function does not return any value"); }
In some scenarios, we may want to pass values only for minimal parameters. In such cases, we can define the properties in an interface as optional properties, as follows:
interface Customer { id: number; name: string; bonus?: number; } function addCustomer(customer: Customer) { if (customer.bonus) { console.log(customer.bonus); } } addCustomer({id: 101, name: "Rajesh Gunasundaram"});
Here, the bonus property has been defined as an optional property by concatenating a question mark (?) at the end of the name property.
