Web Development with Angular and Bootstrap - Sridhar Rao Chivukula - E-Book

Web Development with Angular and Bootstrap E-Book

Sridhar Rao Chivukula

0,0
25,19 €

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

Mehr erfahren.
Beschreibung

Combine the power of Angular, Bootstrap 4, FlexLayout, and Angular Material Design to build elegant user interfaces

Key Features

  • Learn to combine Angular 6 with Bootstrap 4 to design highly intuitive and responsive web interfaces
  • Explore the design principles for professional web layout with Angular Material, Flexbox, and Bootstrap
  • Avoid potential stumbling blocks in web development with the help of expert tips

Book Description

Angular and Bootstrap have undergone a major overhaul to embrace emerging web technologies that help developers build cutting-edge web applications. This book is for you if you're ready to enhance your web development skills beyond HTML and CSS.

It begins with the basics of Angular and Bootstrap 4, along with an introduction to ES and TypeScript. You'll be able to refine your skills further with flex-layout's Responsive API to specify different layouts and sizing for various screen sizes. By using Angular Material, you'll discover how to make your web pages look professional. You'll study how to format output using Angular's pipes and use the built-in router to set up routes for all your components. With the help of Webpack, you'll be able to easily wrap up your project and use SASS to make things pretty. Furthermore, you can validate the forms you've built and debug your application. This book will also guide you in transitioning from Bootstrap to Angular smoothly, hooking up with a server, and using Firebase as the persistence layer. You'll not only develop the right skills, but also gain insights into the potential stumbling blocks and tips for how to avoid them.

By the end of this book, you'll have a stunning e-commerce application running, along with the confidence to build your own applications.

What you will learn

  • Develop Angular single-page applications using an ecosystem of helper tools
  • Get familiar with Bootstrap's new grid and helper classes
  • Embrace TypeScript and ECMAScript to write more maintainable code
  • Implement custom directives for Bootstrap 4 with the ng2-bootstrap library
  • Understand the component-oriented structure of Angular and its router
  • Use the built-in HTTP library to work with API endpoints
  • Manage your app's data and state with observables and streams
  • Combine Angular and Bootstrap 4 with Firebase to develop a solid example

Who this book is for

Whether you already know a little about Bootstrap or Angular or you’re a complete beginner, this book will enhance your capabilities in both frameworks. It will guide you in easily building a fully functional web app. Working knowledge of HTML, CSS, and JavaScript is required to get a better understanding of Bootstrap and Angular.

Sridhar Rao Chivukula is a technical lead at Mindtree Ltd and is based out of New York City. He brings with him more than a decade of rich hands-on experience in all aspects of frontend engineering. He has worked with leading companies such as Oracle, Tech Mahindra, and Cognizant Technology Solutions. He has a Bachelor's degree in Information Technology. He is the author of the books Expert Angular and PHP and Web 2.0 Application Interfaces, published by Packt. Aki Iskandar is an entrepreneur and software architect with over two decades of programming experience. He has worked as a consultant for Microsoft, Compuware, Progressive Insurance, Allstate Insurance, KeyBank, Ernst & Young, and Charles Schwab, to name a few. His last full-time job, before leaving the corporate world in 2011, was at PNC , where he served as an enterprise architect on their Enterprise Architecture team. During that time, he served as a core member on PNC's Architecture Review Board, which was responsible for creating reference architectures, reviewing the architectural diagrams for IT projects that were in the tens of millions of dollars in size, and establishing IT Governance for the corporation. He is the founder of VIZCARO (an online motivational service that helps thousands of people) and maintains a blog focusing on Angular and related technologies.

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 549

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Web Development with Angular and BootstrapThird Edition

 

 

 

Embrace responsive web design and build adaptive Angular web applications

 

 

 

 

 

 

Sridhar Rao Chivukula 
Aki Iskandar

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Web Development with Angular and Bootstrap Third Edition

Copyright © 2019 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.

 

Commissioning Editor: Kunal ChaudhariAcquisition Editor: Larissa PintoContent Development Editor: Keagan CarneiroSenior Editor: Martin WhittemoreTechnical Editor: Jinesh TopiwalaCopy Editor: Safis EditingProject Coordinator: Manthan PatelProofreader: Safis EditingIndexer: Tejal Daruwale SoniProduction Designer: Nilesh Mohite

First published: May 2015 Second edition: November 2016 Third edition: August 2019

Production reference: 1300819

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78883-810-8

www.packt.com

To my dear Bhavya, Pratyush, and Aaradhya for bringing joy, happiness, smiles, and strength into our lives.
– Sridhar Rao Chivukula
 
Packt.com

Subscribe to our online digital library for full access to over 7,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.

Why subscribe?

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

Fully searchable for easy access to vital information

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

Contributors

About the authors

Sridhar Rao Chivukula is a technical lead at Mindtree Ltd and is based out of New York City. He brings with him more than a decade of rich hands-on experience in all aspects of frontend engineering. He has worked with leading companies such as Oracle, Tech Mahindra, and Cognizant Technology Solutions. He has a Bachelor's degree in Information Technology. He is the author of the books Expert Angular and PHP and script.aculo.us Web 2.0 Application Interfaces, published by Packt.

 

 

 

 

 

Aki Iskandar is an entrepreneur and software architect with over two decades of programming experience. He has worked as a consultant for Microsoft, Compuware, Progressive Insurance, Allstate Insurance, KeyBank, Ernst & Young, and Charles Schwab, to name a few. His last full-time job, before leaving the corporate world in 2011, was at PNC , where he served as an enterprise architect on their Enterprise Architecture team. During that time, he served as a core member on PNC's Architecture Review Board, which was responsible for creating reference architectures, reviewing the architectural diagrams for IT projects that were in the tens of millions of dollars in size, and establishing IT Governance for the corporation.

He is the founder of VIZCARO.com (an online motivational service that helps thousands of people) and maintains a blog focusing on Angular and related technologies.

About the reviewer

Phodal Huang is a developer, creator, and author. He works at ThoughtWorks as a senior consultant and focuses on IoT and the frontend. He is the author of Design IoT System, Thinking in Full Stack, and Frontend Architecture in Chinese.

He is an open source enthusiast and has created a series of projects on GitHub. After his daily work, he likes to reinvent some wheels for fun. He created the micro-frontend framework Mooa for Angular. You can discover more wheels on his GitHub page, @phodal.

He loves designing, writing, hacking, and traveling. You can also find out more about him on his personal website at phodal.com.

 

 

 

 

 

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Web Development with Angular and Bootstrap Third Edition

Dedication

About Packt

Why subscribe?

Contributors

About the authors

About the reviewer

Packt is searching for authors like you

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

Quick Start

Angular's evolution

Angular's building blocks

Components

Templates

Directives

Modules

Services

Dependency injection

Setting up your development environment

Writing your first Angular application

Using your development environment

Location of your files

Generating our to-do list application

Serving up our to do list application

Angular basics

Components

Code listing for the to-do list application

Interpolation

Templating and styling

Property binding

Event binding

Our sample project

Annotated photo album

Design principles

Wireframes

Wireframing tools

Wireframes for our annotated photo album

Home page

Dashboard

Image upload

Photo preparation

Create Album

Photo listing

Photo album listing

Workbench

Album viewer

Paper prototyping

Summary

ECMAScript and TypeScript Crash Course

The (quick) roadmap

The relationship between JavaScript and TypeScript

A series of fortunate events for JavaScript

Chromium project

Javascript frameworks

ECMAScript 2015

TypeScript crash course

Transpilation versus compilation 

let

Const

Data typing

Objects 

JSON 

JavaScript runtime environment

Arrays

TypedArray

Maps 

WeakMap

Set

WeakSet

Classes

Interfaces

Inheritance

Destructuring 

Template strings

for-of loop

Decorators

Promises

Modules

Default exports

Summary

Bootstrap - Grid Layout and Components

A word about what this chapter is not

Our example application

Game plan

Sass crash course

What is Sass?

Compass framework

Two SASS styles

Installing Ruby 

Installing Sass

Online tools for Sass

Offline tools for Sass

Sass features and syntax

Nesting

Variables

Mathematical operations

Imports

Extend

Mixins

Placeholders

Built-in functions 

Custom functions

Bootstrap crash course

What is Bootstrap?

Motivation

Bootstrap's role in our example application

Installing Bootstrap

Bootstrap's responsive grid system

The container

The row

The column

Differing viewport sizes

Bootstrap components

Button components

Alert components

Navbar component

Modal components

Listing Carousel – a formal introduction

Idea generation/concept

Analysis — feasibility study

Requirement gathering

Wireframes

Implementation

Installing our interim web server

Welcome page

Signup

Login

Listings

Create listing

Edit listing

Wireframes collection

Summary

Routing

What is routing in Angular?

Creating our application's shell using the CLI

First things first – basic concepts

Base Href

RouterLink and RouterLinkActive

Configuring routes for our application

Parameterized routes

Child routes

Route guards

Completing our route configuration

Bootstrap navigation bar and router links directives

Specifying the location for rendering the component templates

Running our application

Routing strategies

Summary

Flex-Layout - Angular's Responsive Layout Engine

Why this chapter was included in the book

The four available techniques for the layout of our components

Table

Positioning using float, and clear

FlexBox CSS

CSS Grid

Why FlexBox CSS is probably the best option

What is Flex-Layout and why should you use it?

Integrating Flex-Layout

The Flex-Layout API

Design strategies when using FlexBox

Associating our components with the chapters and topics in this book

Implementing our selected wireframes

The Create Listing wireframe

The Edit Listing wireframe

Summary

Building Angular Components

Angular application architecture – a tree of components

Architecting an Angular application

Breaking up your components into sub-components

Component responsibilities

Annotations 

@Component

Properties of the @Component decorator

selector

template and templateUrl

styles and stylesUrls

View encapsulation

Module versus NgModule

Properties of the @NgModule decorator

Content projection

Projecting multiple sections

Life cycle hooks

Most common life cycle hooks

Component interface – inputs and outputs, and the flow of data

Our implementation of the components for our three pages

Summary

Templates, Directives, and Pipes

Templates

Directives

Attribute directives

Structural directives

NgFor

Accessing the index value of the iteration

Built-in directives

NgIf

NgSwitch, NgCase, and NgDefault

NgStyle

NgClass

NgNonBindable

Data binding using the NgModel directive

Event binding

Property binding

Custom directives

Pipes

Custom pipes

Summary

Working with NG Bootstrap

Integrating NGB 

Installing NBG

Why use NGB?

Creating our playground for NGB (and Angular Material, and more)

Creating a playground directory

Creating the playground component class

Creating the playground template file

Creating the playground CSS file

Creating the playground menu item

NGB widgets

Collapse

Our parent component

Our NGB collapse component class

Our NGB collapse component template

Importations and declarations 

Modal

Our NGB modal component class

Our NGB modal component template

Importations and declarations 

Carousel

Our NGB carousel component class

Our NGB carousel component template

Implementing NGB into our example application

UX design rules of thumb

Keep it clean

Keep it functional

Keep it obvious

Summary

Working with Angular Material

What is Angular Material?

Installing Angular Material

Categories of components

Navigation

Navigation components using schematics

Custom Material menus and navigation

Custom sidebar menus

Cards and layout 

Material cards

Lists

Lists with dividers

Navigation lists

Accordions and expansion panels

Steppers

Tabs

Form controls

Buttons and indicators

Popups and modals

Data tables

Summary

Working with Forms

Bootstrap forms

What are forms?

Bootstrap form classes 

Bootstrap form classes – extended 

Sizing

Readonly

Inline forms

Forms using Bootstrap grid classes

Disabled 

Help text inside forms

Displaying input elements as plain text

Angular forms

Template-driven forms

Template-driven forms – pros

Template-driven forms – cons

Template-driven forms – important modules

Building our login form

Model-driven forms, or reactive forms

Model-driven forms – pros

Model-driven forms – cons

Model-driven forms – important modules

Reactive forms – registration form example

Angular form validations

Template-driven form validation

Reactive form, or model-driven form, validations

Submitting form data 

Summary

Dependency Injection and Services

What is DI?

Generating services and interfaces

Guarding against code minification

Summary

Integrating Backend Data Services

ListingApp – an overview

Fundamental concepts for Angular applications

Strongly typed languages

Typescript interfaces

Observables

NoSQL databases concept

CRUD operations – overview

ListingApp – technical requirements

Building APIs for ListingApp

Google Firestore database

Angular HttpClient

HttpClient and HTTP verbs

HTTP GET

HTTP POST

HTTP PUT

HTTP DELETE

HTTP via promises

Integrating backend services 

Integrating Angular HTTP with backend APIs

Integrating Angular HTTP with Google Firebase

Summary

Unit Testing

Introduction to testing frameworks

About the Jasmine framework

About the Karma framework

Angular test automation

Testing Angular components

Testing directives

Testing Angular routing

Testing dependency injection

What is dependency injection?

Testing Angular services

Testing HTTP

Summary

Advanced Angular Topics

Custom directives

Custom form validations

Building single-page applications

User authentication

User authentication with Firebase

User authentication with Auth0

Summary

Deploying Angular Applications

Deploying Angular applications

Compilation options for Angular applications

What is just-in-time compilation?

What is ahead-of-time compilation? 

Deploying a standalone Angular application

Deploying composite Angular applications

Creating and deploying multiple Angular applications

Packing the Angular project as an npm package

Deploying Angular apps to GitHub Pages

Creating and deploying applications in GitHub Pages

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Modern web application development has evolved a lot in recent years. The applications are designed and developed using the mobile-first approach. Angular is every developer's dream framework that is used for rapid prototyping in order to deploy complex enterprise applications. This book will guide you in jump-starting Angular application development using the Bootstrap CSS framework. Each chapter in this book is structured to give you a full understanding of a specific topic and aspect of the Angular framework, along with other related libraries and frameworks. Each of these aspects are essential for designing and developing a robust Angular application. In a step-by-step approach, you will learn about each of the following phases: TypeScript, Bootstrap framework, Angular routing, components, templates, Angular Material, dependency injection, and much more.

By the end of the book, you will be able to create modern, responsive, cross-platform Angular applications using various CSS frameworks, including Bootstrap, Material Design, and NG Bootstrap. 

Who this book is for

This book has been carefully thought through, and its content covers topics ranging from those suitable for absolute beginners to some of the most complex use cases. The detailed explanations, step-by-step hands-on use case examples, and easy flow of this book make it a must-have for your collection. 

This book will benefit developers with little or no programming background, while also benefiting seasoned developers.

What this book covers

Chapter 1, Quick Start, begins your journey with the help of a quick introductory chapter to show you the possibilities available and to get you thinking creatively. 

Chapter 2, ECMAScript and TypeScript Crash Course, examines the TypeScript language, from basic to advanced aspects of the language that are essential when it comes to writing Angular applications.

Chapter 3, Bootstrap – Grid Layout and Components, introduces the awesome Bootstrap CSS framework and explains how you can use some of the components and utilities provided by this supersonic library.

Chapter 4, Routing, enables you to cut your teeth on the Angular framework by learning all about routing. From defining simple route paths to complex route guards and much more, you will be empowered with the knowledge to build rock solid routing systems for your applications.

Chapter 5, Flex Layout – Angular's Responsive Layout Engine, covers alternative layouts and a grid-designing library named Flex Layout, and explains how Flex Layout offers a powerful layout for your Angular applications.

Chapter 6, Building Angular Components, covers Angular components, the main building blocks of modern progressive web applications. You will learn to build multiple components and bring them all together to build views and functionality.

Chapter 7, Templates, Directives, and Pipes, introduces the Angular template engine, directives, and pipes. You will explore the built-in directives, pipes, and templates.

Chapter 8, Working with NG Bootstrap, introduces NG Bootstrap, another super powerful framework that you can consider in your projects. 

Chapter 9, Working with Angular Material, explains the development of our Angular applications using the components, directives, and utilities provided by Angular Material. 

Chapter 10, Working with Forms, introduces the heartbeat of any dynamic application. You will learn about the different approaches to building forms, exploring template-driven forms, reactive forms, and much more.

Chapter 11, Dependency Injection and Services, covers dependency injection, services, and the design philosophy behind the scenes. 

Chapter 12, Integrating Backend Data Services, is where all the code, learning, and hands-on examples that you have learned and built throughout the chapter will come together. You will stitch end-to-end screens, from UIs to components, to services and models, and much more. You will learn everything you need in order to assimilate all aspects of Angular.

Chapter 13, Unit Testing, explains how testing is one of the most important aspects in modern-day software development. This chapter will teach you all about testing Angular applications.

Chapter 14, Advanced Angular Topics, discusses user authentication and powerful user management systems, and also covers the integration of your applications with Google Firebase and Auth0.

Chapter 15, Deploying Angular Applications, examines how to deploy your Angular applications and make them production ready.

To get the most out of this book

To make the most of the information that you will learn in this book, you are encouraged to do a quick recap of programming fundamentals, including classes, objects, loops, and variables. This can be in any language of your choosing. Angular applications are not limited to any particular operating system, so all that is required is a decent code editor and a browser. Throughout the book, we have used Visual Studio Code editor, which is an open source editor and is free to download.

Download the example code files

You can download the example code files for this book from your account at www.packt.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.packt.com

.

Select the

 

Support

 

tab.

Click on

 

Code Downloads

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/PacktPublishing/Web-Development-with-Angular-and-Bootstrap-Third-Edition. 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!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The screenshot shows the editedangular.jsonfile."

A block of code is set as follows:

"styles": [ "styles.css", "./node_modules/bootstrap/dist/css/bootstrap.min.css"],"scripts": [ "../node_modules/jquery/dist/jquery.min.js", "./node_modules/bootstrap/dist/js/bootstrap.min.js"]

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

import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { AppComponent } from './app.component';

import { JacketListComponent } from '../../projects/jackets/src/app/jacket-list/jacket-list.component';

import { VendorsComponent } from '../../projects/vendors/src/lib/vendors.component';

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

ng new realtycarousel

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "We have added the menu link,Add New Listing."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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/support/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.

Reviews

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

Quick Start

Are you ready to work your way to Angular mastery? My guess is that you are, and with this book and your determination, you will. You purchased this book, and I not only thank you, but I want to make a promise to you right here, right now. Two promises, in fact. The first one is that if you diligently read the material, apply the knowledge you'll gain along the way, and build the example application with me throughout these pages, you will be well on your way to Angular mastery.

If you're anything like me, you have a library packed with literally hundreds of technical books and you have read most of them. Some books start off at an excruciatingly slow pace, entrenched in theory and historical minutia, while other books start off so quickly, they leave the readers scratching their heads wondering if they are too dumb to understand the material. The truth is, striking a balance while introducing readers to potentially brand new material—and not have them nod off as they read their newly acquired 400+ page technical book—is a tricky thing to pull off. So, my esteemed budding Angular guru, that is what my second promise is to you. I promise to do my utmost in finding that all-elusive happy medium between being technically heavy-handed, and being real-world practical while making this book as entertaining a read as I possibly can for you.

With the promises well stated, let's start our journey to Angular mastery together by taking a quick look at what we're going to cover in this brisk, but all important first chapter.

We'll set up your development environment in a jiffy, and we'll build our first Angular application in order to get some immediate feeling of accomplishment. We're going to skim over the details as we write it, but right after that, we'll cover a few critical Angular basics in more detail before concluding this chapter. These first few basics are the very first things you should get comfortable with because we'll use them over and over again throughout the book as we learn about the more advanced stuff.

After we cover these basics, we'll switch gears from Angular speak and we'll take a look at the fully fledged application that we'll be building together throughout the remainder of the book. As a bonus (and there are a few bonuses in this book that I hope will bring you a bunch of value), we're also going to touch on design principles, wireframing, and a little used design strategy called paper prototyping—whose focus is on usability testing. Paper prototyping has been around since approximately 1985 and has largely been replaced by Lean UX design since approximately 2008. Still, I'm always amazed at how many of my clients have never even heard of paper prototyping—but I'm also happy when they discover the value it brings to them when they try it out.

We'll cover paper prototyping at a high level at the end of this chapter, immediately following the wireframes section, which is the most logical place for discussing paper prototyping. We'll touch on a few UX design principles as well, but not on the Lean UX process itself since that would take us too far off course from our focus of this book. However, if you have an interest in the Lean UX design process, here is a good starting point: https://www.interaction-design.org/literature/article/a-simple-introduction-to-lean-ux.

OK, my esteemed budding Angular guru, are you primed and ready to get started? Good! Let's go!

The topics we will be covering in the chapter are:

Angular's evolution

Angular's building blocks

Setting up your development environment

Writing your first Angular application

Angular basics

Our sample project

The process of paper prototyping

Angular's evolution

Angular is a frontend JavaScript-based web application framework that provides you with everything you need, including the kitchen sink, with which to build amazingly powerful Single Page Applications (SPAs). The application we'll be building together is an SPA, and we'll be discussing SPA strategies along the way.

While Angular wasn't the first JavaScript-based frontend web application framework, it was quite possibly the most powerful one of them. This is likely due to Angular's SPA-centric focus—since there's more to building an SPA application than there is to simply provide two-way data binding on your web pages.

The initial release of Angular was in late fall of 2010. Since then, dozens of competing libraries and frameworks have come on the scene, including some that also have large adoptions and large production implementations, such as Ember.js, Backbone.js, and React.js. Angular, despite having perhaps the highest learning curve (and we'll see why this is the case), remains the most powerful one of them all.

The Angular naming and versioning jungle can, at first glance, seem confusing. There are a few reasons for this, as follows:

Angular's 1.x releases

: Basically, any release prior to Angular 2 is commonly referred to as AngularJS. 

AngularJS is no more actively in development mode. It has been put under long term support mode.

Angular framework is being actively

 developed, and so developers need to be specific about which of the two Angular frameworks they are referring to when discussing them. Fortunately, there are two completely dedicated websites for them:

 

https://angularjs.org/

 and

https://angular.io

, respectively. The Angular team adopted semantic versioning, starting with the 2.0.0 release. You can read more about semantic versioning here:

https://semver.org

.

Angular 2 was a complete rewrite of Angular 1.x (that is, AngularJS), and is thus not backward compatible with AngularJS. While Angular 4 was not a complete rewrite of Angular 2, it did have some changes in its core libraries that required the team to increment its major number from 2 to 4. Version 3 was skipped as a release number altogether.

All releases from Angular 2 onward are commonly referred to as Angular 2+, or simply just as Angular.

Due to having adopted semantic versioning, the Angular team never released Angular 3 and so went straight from Angular 2 to Angular 4. Specifically, there was a misalignment of the router package's version, which was already distributed as version 3.3.0. We'll cover routing in Angular in great detail in

Chapter 4

,

Routing

. Don't let this confuse you. Just know that there wasn't ever an Angular 3. No big deal. In the Windows OS world, there was never a Windows 9 either. These things happen.

After reading the preceding list, you can see why there tends to be some confusion around Angular. However, it's pretty straightforward if you keep these two things in mind:

You should really only be using Angular, and not AngularJS (unless you have an exceptionally good reason for it)

With the exception of there not being an Angular 3, there will be two major releases per year; they should be contiguous in numbering scheme (that is, 8, 9, and so on), and they are expected to be backward compatible—at least within the same major version number (as per the spirit of semantic versioning)

You can check out the official Angular release schedule here: https://github.com/angular/angular/blob/master/docs/RELEASE_SCHEDULE.md. Since Angular is a complete rewrite of the AngularJS platform, and this is worlds apart from AngularJS, we'll skip AngularJS altogether and start by taking a look at Components which are Angular's building blocks. Are you with me? Great, let's speedily move ahead.

Angular's building blocks

Adding new features is the business of publishing new frameworks—but luckily, the fundamental underlying architecture does not change very often. When it does, it's not typically a complete overhaul. With the exception of Angular 2.0, which was completely divergent from its predecessor, all major releases so far contain largely the same architecture.

Let's now take a look at the core architectural pieces of the framework.

Components

Components are like widgets that are in charge of displaying themselves along with the data they consume and/or manipulate on areas of your screen called views. An Angular application is like a tree of components, and Angular provides mechanisms for components to communicate with each other in a bidirectional manner—parent to child and child to parent.

Templates

Components rely on their templates for rendering their data. Templates are where you define what the component looks like and you can hook in styles to window-dress your component any way you like. A component can either contain its template (that is, the HTML) and its styling (that is, the CSS) either directly within itself or have references to template and style files outside of itself. At the end of the day, the world's fanciest frontend frameworks produce HTML, CSS, and JavaScript because these three things are the only things browsers understand.

Directives

Within the templates you create for your component, Angular enables you to alter the DOM with powerful constructs called directives. There are directives for controlling the way things are rendered on the screen (that is, the component view) such as repeating snippets of HTML, for displaying things based on conditional logic, for hiding or showing things, filtering arrays of data, and much more.

Modules

Angular is modular. That is to say that its functionality is wrapped up in modules, known as NgModules, and are themselves libraries. Modules are perfect for lumping code together in an organized way. For instance, there are modules for helping with forms, routing, and communicating with RESTful APIs. Many third-party libraries are packaged as NgModules so you can incorporate them into your Angular applications. Two examples of this are Material Design and AngularFire—we'll be taking a look at both of these libraries in later chapters.

Services

Services are not really an Angular artifact per se, but rather a very general notion representing encompassed functionality, functions, and features that your application's components may need to consume. Things such as logging, data retrieval, or virtually any calculation or lookup service, can be written as services—these services can reside within your application, or live externally from it. You can think of a service as a highly specialized class that provides some service (such as looking up the distance between two zip codes) and does it well. Just as with components, not only are there tons of third-party services you can use in your Angular applications, but you can create your own custom services. We'll learn how to do this in Chapter 12, Integrating Backend Data Services.

Dependency injection

Dependency injection(DI), or Inversion of Control (IoC), is a very useful and common software design pattern. This pattern is used to inject objects into the objects that depend on them. The object you're using that depends on other objects can just go ahead and use it without needing to worry where it is in order to load it, or how to instantiate it—you just use it as if it just sprung into existence at the time you needed it. Services are perfect for injecting into our application. We'll learn how to use DI in Angular, and how we can use the Angular command-line interface (CLI ) to generate injectable services of our own design.

Just before we move on to setting up our development environment, here are some interesting things about Angular:

AngularJS was built using JavaScript, while Angular was built using TypeScript. While this adds a level of abstraction when writing Angular applications, using TypeScript provides a few important advantages when building larger apps with larger teams—we'll get to those shortly.

AngularJS was based on controllers, whereas Angular is component based. You'll learn all you need to know about components in

Chapter 6

,

Building Angular Components.

SPAs are notorious for being difficult for implementing

Search Engine Optimization

(

SEO

 

), but Angular is SEO friendly.

It's possible to build native mobile applications with Angular.

It's also possible to build cross-platform, desktop-installed applications with Angular.

Angular can also run on the server, using Angular Universal.

You have to admit, this is a pretty impressive and exciting list. These things and more make learning Angular a worthwhile endeavor and the marketplace is asking for Angular know-how.

Setting up your development environment

In order to get started with Angular, you're going to need to have the Angular CLI installed; to install that, you first need to have Node.js and npm (node package manager) installed. If you've already got Node.js and npm installed, great! If not, don't worry—they are easy to install and I will take you through the installation process in Appendix A, Toolchain for Web Development with Angular, near the back of the book. In Appendix A, I also take you through installing the Angular CLI and how to use it for building Angular applications. For brevity, I'll refer to the Angular CLI tool as just the CLI from this point forward.

If you are unsure whether you have NodeJS and npm installed, you can check really quickly by typing $ node -v and $ npm -v, respectively, on your command line. Similarly, you can type $ ng -v on the command line to see whether you have CLI installed. If you get a version number back, you have that particular tool installed (as shown in the following screenshot I took).

Note: Do not type $ at the beginning of the commands. The $ signifies the command prompt, entry point for the commands you'll type. Unix-based operating systems, such as macOS and Linux systems, commonly use $ or % as their command prompt—depending on the shell being used, or if there are any custom settings specified in a configuration file on your system. Windows operating systems typically use the greater than sign, >, as their command prompt.

If any of these commands go unrecognized, jump on over to Appendix A real quick, install the tools, and jump right back here. I'll be waiting for you.

We'll also need a code editor. There are many code editors available today, including a number of free ones. Though any code editor will suffice, I would suggest you use Visual Studio Code for your Angular development—at least while working through this book. The reason for this is that Visual Studio Code is free, it's cross-platform, and is an excellent code editor. It's also the code editor that I've used while writing this book and so when I suggest the use of an extension, you can easily install the same one.

The preceding is all you need for this first chapter. When we start building the example project, which requires us to have a local database, you'll also need to install MongoDB. MongoDB, also known as Mongo, is a great NoSQL database that is also free and cross-platform. I take you through Mongo's installation process in Appendix B, MongoDB.

Additionally, there will be other software that you'll need to install, such as Chrome extensions, and I will let you know what they are and where to find them at the appropriate time. For now, let's get started with writing some Angular code.

Writing your first Angular application

When it comes to experimenting with Angular code, as you pick up this awesomely powerful framework, you generally have two choices of how to proceed. The first is to use an online code editor such as JSFiddle, Plunker, StackBlitz, or more. In Appendix C, Working with StackBlitz, you'll learn about the basics of using StackBlitz so you can use it from time to time to test some quick code without needing a test project in your development environment. You can visit the StackBlitz website here: https://stackblitz.com.

The second approach is to use your own local development environment—and since we've already set it up in the previous section, you can create a project whose sole purpose is to run some quick example code if you'd rather use that than an online code editor. My goal is to show you that you have options—there's not just one way to experiment with some code as you learn Angular.

When you use an online code editor, such as StackBlitz, the only software you need installed is a browser—no other tools whatsoever. While this makes things very easy, the trade-off is that you are extremely restricted in what you can do. That being said, I encourage you to experiment with an online code editor, but we'll only be using our development environments throughout this book. So, let's do that and create a small application together in just a few minutes time—we'll build a to-do list app.

Using your development environment

From this point forward, we'll be using our terminals, the CLI, and the Visual Studio Code. Head on over to https://code.visualstudio.com, where you'll be able to download the Visual Studio Code installation package for your operating system of choice.

Location of your files

When it comes to setting up a local environment, you can, of course, place your directories and files wherever you like. If you have a folder where you have your web application projects, go to it now. If you don't have a dedicated place for projects, this is as good a time as any to get into the habit of being organized. For instance, on my machine, I have a folder named dev for any and all development I do. Within my dev folder, I have a folder named playground, where I have a subfolder for each technology I'm learning, or playing with. I prefer to use a Mac when writing code, and so my complete pathname to where I have my Angular play stuff is /Users/akii/dev/playground/angular (as shown at the bottom of the screenshot of my terminal, a few pages back). That same screenshot also shows the versions of Node.js, npm, and the CLI that I had installed at the time of writing. If having a directory structure like this works for you, by all means, use it. If you already have a way you organize your work, use that. The important thing is to be very disciplined and consistent with how you organize your development environment.

Generating our to-do list application

With the installation of what we need now being out of the way—meaning we have our CLI tool available to us—go to your terminal and type the following at your command prompt $ ng new to-dolist --style=scss --routing, and then hit Enter.

The ng command runs the CLI tool, and its new command instructs it to create a new Angular application. The application, in this case, is named to-dolist. You'll notice that there also are two command-line flags, which are special options for the new command. The style flag tells the CLI that we'd like to use scss, instead of css, and the routing flag tells the CLI that we'd like it to integrate and set up routing for us by default. We'll be using SASS, as opposed to CSS, in this book, and SCSS is the file extension for Sass files. As a reminder, we're going to have a crash course on Sass in Chapter 3, Bootstrap – Grid Layout and Components.

The first time you use the CLI to create your Angular application, it will take anywhere from 45 seconds to well over a minute for it to create your project for you. This is because it needs to download and install various things for you before it creates the project's folder structure. However, when creating subsequent Angular applications, the CLI won't take nearly as long.

Serving up our to do list application

Once the CLI has completed creating the application, you can run it by changing to the project directory ($ cd to-dolist) and issuing the $ ng serve command. This will have the CLI run your application. The CLI's built-in web server will be listening on localhost port 4200 by default. By the way, the CLI's web server keeps watch on your project files, and when it notices a change in one of your files, it reloads the application—there's no need for you to stop the server and issue the server command again. This is very convenient as you're making lots of changes and tweaks during development. Next, open your browser and visit http://localhost:4200 and you should see something like the following, which proves that the CLI is working correctly:

Now that the CLI created the to-do list application for you, open that folder in Visual Studio Code (note: for brevity, I'll be referring to Visual Studio Code as the IDE). You should see a folder structure for your to-do list project in the left-hand panel of your IDE, similar to the following (except for the to-do folder, which you won't have just yet; we'll get to how to generate that using the CLI in the upcoming subsection on components).

The following is a screenshot of the to-dolist project in the IDE (with the app.component.ts file open):

When working on your Angular applications, the vast majority of your time will be spent working within the src | app folder.

Angular basics

Components are the basic building blocks of Angular. In fact, you can think of an Angular web application as a tree of components. When you use the CLI to generate the shell for your Angular application, the CLI also autogenerates one component for you. The filename is app.component.ts and is in the src/app folder. The app component is how your Angular application is bootstrapped—meaning that it is the first component that is loaded, and all the other components are pulled into it. This also means that components can be nested. The previous screenshot shows our project directory structure, with the src/app folder expanded, and the app.component.ts open in the IDE's file editor window. The .ts file extension indicates that it is a TypeScript file. Interesting note—when you write Angular applications, you use TypeScript instead of JavaScript. In fact, the Angular team used TypeScript to write Angular!

After the following Components section, you'll find a complete code listing for our Angular application. There are six files that you'll have to edit. Three of them are already available in the application that you generated with the CLI. The other three will be available in your project once you use the CLI to generate the to-do component, which is the directory that you are presently missing when you compare your project structure to the previous screenshot. You'll find out how to do that in the following Components section, which is why the complete code listing was inserted afterward. Don't worry—follow along, keep the faith that Angular mastery is within your grasp, and you'll be just fine. If you don't believe me, just lie down on the floor and mumble these words, This too, shall pass, three times, slowly.

Interpolation

Interpolation is how you get a value from a variable within your component class to render in the component's template. If you recall, the logic for the component goes in the export section of the component class. That is the same place where variables are that you would like to use interpolation to have their values rendered in the template (that is, rendered on the web page). Let's assume that you have a variable called items and that its value is currently 4. To render the value in the template, you use a pair of double curly braces with the variable in between them. The variables and component logic are written inside the class.

Don't worry—we'll see lots of code snippets throughout the book that use interpolation, but for now, you can see this sample code that shows it in action. The code is meaningless and hardcoded for now, but it does demonstrate interpolation.

The first screenshot is of the component file (home.component.ts); the variable is declared on line 10:

This second screenshot is of the component's template file (home.component.html). Notice the pair of double curly braces on line 6:

This last screenshot shows the rendered value, 4 in this case. That's the basics of interpolation. We'll see much more advanced usage of it throughout the book as we work on our annotated photo album:

Templating and styling

We've already mentioned something about templating and styling in the last few paragraphs of the Components section. Now that we have a small project available to us—the one that we created with the CLI—we can see what this looks like in code. Open your Angular project in the IDE, and open the app.component.ts file. Lines 5 and 6 in this app component file contain the references to its associated template (the .html file), and its style file (.scss), respectively. The following is a screenshot of the open project in my IDE, with the app.component.ts file open:

Property binding

There are two types of data binding we can do in Angular, namely, one-way and two-way. Interpolation is very similar to one-way data binding. This is because, in both cases, data flows from the component class to the component template and not the other way around. Property binding is data binding in the sense that the data is being bound to a property.

It's also possible to have two-way property binding—meaning, not only can the value of a component property be bound to the template, but the template can alter the value of a component property. This is made possible in Angular by ngModel. Again, don't worry about this for now. We will take a look at two-way property binding later on. Just know that both one-way and two-way property binding is possible in Angular.

Implementing one-way property binding is very straightforward. All you need to do is to put square brackets around the HTML property (in the component's template) you want the data bound to, and assign the variable to it. To see a quick example of what one-way property binding looks like in code, take a look at the next three screenshots.

The first screenshot is of the component file (home.component.ts); the variable, txtPlaceholder, is declared on line 11:

This next screenshot is of the component's template file (home.component.html). In line 14, you can see the square brackets around the placeholder property of the input element:

This last screenshot is of the application running in the browser. You can see the text, Enter your todo item here, inserted as the placeholder text for the textbox via one-way property binding:

Event binding

In Angular, event binding simply means that an event will be registered on an element within a component, and when that event happens, it will trigger a function to be called. In other words, an event will call a function. There are a ton of events that you can have Angular listen for—such as a button being clicked, a mouse hovering over an image, or when the user presses a key down when the cursor is in a textbox, and lots more. And, of course, you can write any function you can possibly think of to make other stuff happen, such as calling a web service, changing the color of the background page, calculating the value of Pi to 1,000 decimal places, or virtually anything else your heart desires. But how can we set up event binding in our Angular application to tie the event we're interested in, on the element we're interested in, to run the function we want? Well, thankfully, the Angular team made this super easy for us.

Suppose we'd like to have some user interaction via events such as click or mouseover—we can use event binding to map the functionality.