Mastering Angular Components - Gion Kunz - E-Book

Mastering Angular Components E-Book

Gion Kunz

0,0
31,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

Mastering Angular Components will help you learn how to invent, build, and manage shared and reusable components for your web projects. Angular components are an integral part of any Angular app and are responsible for performing specific tasks in controlling the user interface.
Complete with detailed explanations of essential concepts and practical examples, the book begins by helping you build basic layout components, along with developing a fully functional task-management application using Angular. You’ll then learn how to create layout components and build clean data and state architecture for your application. The book will even help you understand component-based routing and create components that render Scalable Vector Graphics (SVG). Toward the concluding chapters, you’ll be able to visualize data using the third-party library Chartist and create a plugin architecture using Angular components.
By the end of this book, you will have mastered the component-based architecture in Angular and have the skills you need to build modern and clean user interfaces.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 474

Veröffentlichungsjahr: 2018

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.



Mastering Angular ComponentsSecond Edition
Build component-based user interfaces using Angular
Gion Kunz
BIRMINGHAM - MUMBAI

Mastering Angular Components Second Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), 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.

Acquisition Editor:Reshma RamanContent Development Editor:Flavian VazTechnical Editor:Akhil NairCopy Editor:Safis EditingProject Coordinator:Devanshi DoshiProofreader:Safis EditingIndexer:Tejal Daruwale SoniGraphics:Jason MonteiroProduction Coordinator:Nilesh Mohite

First published: June 2016 Second edition: July 2018

Production reference: 1170718

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

ISBN 978-1-78829-353-2

www.packtpub.com

To our baby daughter, Zoé. The day of your birth in March 2018 was the most exciting day of my life. Looking into your eyes and seeing you smile makes my heart jump. I love you.

– Gion Kunz
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

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

Mapt is fully searchable

Copy and paste, print, and bookmark content

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.

Contributors

About the author

Gion Kunz has over 12 years of experience in writing interactive user interfaces using JavaScript. He's worked with AngularJS since 2012, is an early adopter of Angular 2 and loves to speak about Angular at conferences.

In 2018 he founded his own company Syncrea, where he helps customers create websites and applications using frontend web technologies. Besides working for his clients, Gion is a tutor at the SAE Institute in Zurich and loves to get his students enthusiastic about the web.

I'd like to thank my family, friends and everyone who supports me in my life. Especially, I'd like to thank you, my love, for all the support, patience and energy you've invested to help me complete this book.

About the reviewer

Phodal Huang is a developer, creator, and author. He works in ThoughtWorks as a Senior Consultant, and focuses on IoT and frontend. He is the author of Design IoT System and Growth: Thinking in Full Stack in Chinese.

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

He loves designing, writing, hacking, traveling, you can also find out more about him on his personal website at phodal(dot)com.

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

Mastering Angular Components Second Edition

Dedication

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the author

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

Component-Based User Interfaces

Thinking in components

Components – the organs of user interfaces

Encapsulation

Composability

Components, invented by nature

My UI framework wishlist

Time for new standards

Template elements

Shadow DOM

Angular's component architecture

Everything is a component

Your first component

Angular NgModule

JavaScript of the future

I speak JavaScript, translate, please!

Classes

Modules

Template strings

TypeScript

History with TypeScript in Angular

Decorators

Tools

Node.js and npm

Angular CLI

Summary

Ready, Set, Go!

Managing tasks

Vision

Starting from scratch

Main application component

Resource download

Main application NgModule

Bootstrapping

Running the application

Recap

Creating a task list

Recap

The right size of components

Recap

Adding tasks

Recap

Custom UI elements

Recap

Task data service

Recap

Filtering tasks

Recap

Summary

Dealing with Data and State

Reactive programming with RxJS

HTTP client and in-memory web APIs

Using behaviour subjects

Loading data in the task service

Subscribing in the view using the async pipe

Recap

Immutability

Immutability with TypeScript

Pure components

Introducing container components

Purifying our task list

Summary

Thinking in Projects

Moving into projects

Project service

Project component

Updating the task list container

Integrating the project component

Recap

Creating a tabbed interface component

Building the main navigation

Composition using content projection

Creating navigation components

Providing a project navigation

Recap

One editor to rule them all

Creating an editor component

Integrating the editor component

Recap

Dealing with users

User service

User area component

Integrating the user area component

Building a commenting system

Introducing a model for comments

Building the comment component

Building the comments component

Integrating the commenting system into projects

Recap

Summary

Component-Based Routing

An introduction to the Angular router

Composition using the router

Routing with container components

Router configuration

Back to the routes

Composing projects using the router

Child routes for project details

Guarding our projects

Summary

Keeping up with Activities

Creating a service for logging activities

Logging activities

Leveraging the power of SVG

Styling SVG

Building SVG components

Building an interactive activity slider component

Projection of time

Rendering activity indicators

Bringing it to life

Recap

Building the activity timeline

Summary

Components for User Experience

Tag management

A model for our tags

Creating a tags service

Rendering tags

Integrating tags using a pipe

Supporting tag input

Creating a tag input directive

Creating a tags select component

Integrating tag selection within the editor component

Integrating tag selection in project comments

Finishing up our tagging system

Drag and drop

Updating our model for ordering tasks

Implementing the draggable directive

Implementing a drop target directive

Integrating drag and drop

Recapitulate on drag and drop

Summary

Time Will Tell

Task details

Navigating to task details

Enabling tags for tasks

Managing efforts

No-UI time duration input

Components to manage efforts

The visual efforts timeline

Recapitulating on efforts management

Summary

Spaceship Dashboard

Introduction to Chartist

Projects dashboard

Creating the projects dashboard component

Project summary component

Integrating the projects dashboard

Creating your first chart

Processing activity data

Creating an activity chart

Visualizing open tasks

Preparing task data

Modeling the problem

Creating an open tasks chart

Creating a chart legend

Making the tasks chart interactive

Summary

Putting Things to the Test

An introduction to Jasmine and Karma

Karma and integration to Angular CLI

Writing our first test

Spying on component output

Utilities to test components

Injecting in tests

Using TestBed for running Angular tests

Component fixture

Mocking child components

Mocking services

Testing components in action

Testing component interaction

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Web components have long been touted as the next great leap forward in web development. With the new version of the Angular framework, we're closer than ever. Over the past couple of years, there's been a lot of buzz around web components in the web development community. New component-style directives in Angular will change developers' workflows and their thinking about shared and reusable blocks of custom HTML in the shadow DOM. By building a whole application from scratch, this book is a practical way to learn, giving readers the chance to build components of their own. With Mastering Angular Components, learners will get ahead of the curve in a new wave of web development by focusing on an area that's the key to unlocking the powers of Angular development.

Mastering Angular Components teaches readers to think in a component-based way when developing user interfaces. This rich guide to the new component-centric way of doing things in Angular teaches readers how to invent, build, and manage shared and reusable components for their web projects. This book will change how developers think about how to accomplish things in Angular, and the reader will work on useful and fun example components throughout.

Who this book is for

This book is for frontend and full-stack developers who already have a good understanding of basic frontend web technologies, such as JavaScript, HTML, and CSS. You will learn about the new component-based architecture in Angular and how to use it to build modern, clean user interfaces.

What this book covers

Chapter 1, Component-Based User Interfaces, looks at a bit of the history of UI development and provides a brief introduction to component-based user interfaces in general. We will see how Angular 2 handles this concept.

Chapter 2, Ready, Set, Go!, gets the reader started on their journey toward building an Angular 2 component-based application. It covers the basic elements of structuring an application with components.

Chapter 3, Dealing with Data and State, focuses on how to build a clean data and state architecture into our application. We'll learn about reactive programming using RxJS, the pure component, the container component, and many more concepts, and tools that can be used to combat application state mess.

Chapter 4, Thinking in Projects, focuses on the structure of the user interface and its basic components. Readers will compose an application by organizing an application layout into components, establishing the composition of components, and creating a reusable tab component to structure the application interface. Readers will also build a re-usable editor component and a commenting system.

Chapter 5, Component-Based Routing, explains how components react to routing and enables readers to add simple routing to existing components in the task management application. Readers will also work on the login process and gain an understanding of how to protect components using the router.

Chapter 6, Keeping Up with Activities, covers the creation of components that will visualize activity streams on both the project and task levels.

Chapter 7, Components for User Experience, guides readers on creating many small reusable components that will have a great effect on the overall user experience of the task management application. Benefits include the in-place editing of text fields, infinite scrolling, popup notifications, and drag-and-drop support.

Chapter 8, Time Will Tell, focuses on creating time-tracking components that help estimate time on a project and task level, but also for users to log the time they spend on tasks.

Chapter 9, Spaceship Dashboard, focuses on creating components to visualize data in the task management application using the third-party library Chartist.

Chapter 10, Putting Things to the Test, covers some basic approaches to testing Angular components. We will look at the options for mocking/overriding specific parts of a component for testing.

To get the most out of this book

This book will need a basic installation of Node.js on your Windows, Mac, or Linux machine. Since this book relies on Angular CLI 6.0.8, at least Node.js 8.9.0 is required.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Mastering-Angular-Components-Second-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 athttps://github.com/PacktPublishing/. Check them out!

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

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

Component-Based User Interfaces

Although we'll cover a lot of Angular-related topics in this book, the focus will be mainly on creating component-based user interfaces. It's one thing to understand a framework like Angular, but it's a whole different thing to establish an effective workflow using a component-based architecture. In this book, I'll try to explain the core concepts behind Angular components and how we can leverage this architecture to create modern, efficient, and maintainable user interfaces.

Besides learning all the necessary concepts behind Angular, together, we will create a task-management application from scratch. This will allow us to explore different approaches to solve common UI problems using the component system that is provided by Angular.

In this chapter, we will take a look at how component-based user interfaces help us build greater applications. Over the course of this book, we will build an Angular application together, where we will use the component-based approach to its full potential. This chapter will also introduce you to the technologies that are used in this book.

The topics that we will cover in this chapter are as follows:

An introduction to component-based user interfaces

Encapsulation and composition using component-based user interfaces

Evolution of UI frameworks

The standard web components

An introduction to the Angular component system

Writing your first Angular component

Basics of

NgModule

An overview and history of ECMAScript and TypeScript

ECMAScript 7 decorators as meta annotations

An introduction to Node.js-based tooling using Angular CLI

Thinking in components

Today's user interfaces do not consist of just a bunch of form elements that are cobbled together onto a screen. Modern users experience designing innovative visual presentations of interactive content challenges technology more than ever.

Sadly, we almost always tend to think in pages when we flesh out concepts for web applications, such as the pages within a printed book. Thinking about a book, this is probably the most efficient way to convey information for this kind of content and medium. You can skim through the pages one by one without any real physical effort, read paragraph by paragraph, and just scan through the chapters that you don't find interesting.

The problem with thinking in pages too much is that this concept, which is borrowed from books, does not really translate well to how things work in the real world. The world is created from components that form a system of components together.

Take our bodies as an example. We mostly consist of independent organs that interact with each other using electrical and chemical signals. Organs themselves consist of proteins that, on their own work, like machines to form a system. Down to the molecules, atoms, protons, and quarks, we can't really tell where one starts and where it ends. What we can tell for sure is that it's all about systems of components with inter-dependencies, and it is not about pages.

Modern user interfaces are very much like the real world consisting of systems of components. If, where, and how they are distributed to pages is subordinate while designing them. Also, they should work independently, and they should interact with each other on an interdependent level.

Components – the organs of user interfaces

"We're not designing pages, we're designing systems of components." - Stephen Hay

This quote by Stephen Hay from BDConf in Orlando 2012 brings it to the point. Interface design is really not about pages. To create efficient user interfaces for not only the users but also the developers who maintain them, we need to think in systems of components. Components are independent, but they can interact with each other and create larger components when they are arranged together. We need to look at user interfaces holistically, and using components enables us to do this.

In the following topics, we're going to explore a few fundamental aspects of components. Some of these are already known from other concepts, such as object-oriented programming (OOP), but they appear in a slightly different light when thinking about components.

Components, invented by nature

Components, embracing encapsulation, and composition are an effective way to build maintainable applications. Composed from components, applications are very resistant to the negative implications of change, and change is a necessary thing that will happen to every application. It's only a matter of time until your design will be challenged by the effects of change; therefore, it's very important to write code that can handle change as smoothly as possible.

Nature is the best teacher. Almost all the achievements in technological developments have their origin in observations of how nature solves problems. If we look at evolution, it's an ongoing redesign of matter by adapting to outer forces and constraints. Nature solves this by constant change using mutation and natural selection.

If we project the concept of evolution onto developing an application, we can say that nature does actually refactor its code in every single moment. This is actually the dream of every product manager—an application that can undergo constant change but does not lose any of its efficiency.

I believe that there are two key concepts that play a major role in nature that allows it to apply constant change in its design without losing much efficiency. This uses encapsulation and composition. Coming back to the example of our bodies, we can actually tell that our organs use a very clear encapsulation. They use membranes to create isolation, veins to transport nutrition, and synapses to send messages. Also, they have interdependencies, and they communicate using electrical and chemical messages. Most obviously, they form larger systems, which is the core concept of composition.

Of course, there are many other factors, and I'm not a professor in biology. However, I think it's a fascinating thing to see that we have learned to organize our code very similarly to how nature organizes matter.

The idea of creating reusable UI components is quite old, and it was implemented in various languages and frameworks. One of the earliest systems that used UI components was probably the Xerox Alto system back in the 1970s. It used reusable UI components that allowed developers to create an application by composing them on a screen where users could interact with them:

The user interface of file manager on the Xerox Alto system from the 1970s

Early frontend UI frameworks, such as DHTMLX, Ext JS, or jQuery UI implemented components in a more limited fashion that didn't provide great flexibility or extensibility. Most of these frameworks just provided widget libraries. The problem with UI widgets is that they mostly don't embrace the pattern of composition enough. You can arrange widgets on a page and they provide encapsulation, but with most toolkits, you can't create larger components by nesting them inside each other. Some toolkits solve this by providing a special kind of widget which was mostly called a container. However, this is not the same as a full-fledged component tree that allows you to create systems within systems. Containers were actually meant to provide a visual layout container rather than a composite container to form a larger system.

Usually, when working with widgets on a page of our application, we'd have a large controller that controls all these widgets, user input, and states. However, we are left with two levels of composition, and there's no way that we can structure our code more granularly. There is the page and there are the widgets. Having a bunch of UI widgets is simply not enough, and we are almost back to the state where we create pages plastered with form elements.

I've been a user of JavaServer Faces for years, and besides all its problems, the concept of having reusable custom elements was groundbreaking. Using XHTML, one could write so-called composite components that consisted of other composite components or native HTML elements. A developer could gain a fantastic level of reusability using composition. In my view, the big issue with this technology was that it did not address the concerns in the frontend enough to become really usable for complex user interactions. In fact, a framework like this should live completely within the frontend.

My UI framework wishlist

Usually, when UI frameworks get compared, they get measured against each other based on metrics, such as widget count, theming capabilities, and asynchronous data retrieval features. Each framework has its strengths and weaknesses, but leaving all the extra features aside and reducing it to the core concerns of a UI framework, I only have a few metrics left that I'd like to be assessed. These metrics are, of course, not the only ones that are important in today's UI development, but they also are the main factors toward building a clean architecture that supports the principle of change:

I can create encapsulated components with clear interfaces

I can create larger components by using composition

I can make components interact with each other within their hierarchy

If you're looking for a framework which enables you to take full advantage of component-based UI development, you should look for these three key measures.

First of all, I think it's very important to understand the main purpose of the web and how it evolved. If we think of the web in its early days in the 1990s, it was probably only about hypertext. There were very basic semantics that could be used to structure information and display them to a user. HTML was created to hold structure and information. The need for custom visual presentation of information led to the development of CSS right after HTML started being widely used.

It was in the mid 1990s when Brendan Eich invented JavaScript, and it was first implemented in Netscape Navigator. By providing a way to implement behavior and state, JavaScript was the last missing piece for a full web customization:

Technology

Concern

HTML

Structure and information

CSS

Presentation

JavaScript

Behavior and state

We have learned to keep these concerns as separate as possible in order to maintain a clean architecture. Although there are different opinions on this and some recent technologies also move away from this principle, I believe that a clean separation of these concerns is very important to create a maintainable application.

Leaving this view aside, the standard definition of encapsulation from OOP is just concerned about coupling and isolation of logic and data. This probably applies well to classic software components. However, as soon as we consider a user interface as part of an architecture, there is a new dimension that is added.

Classical MVC frameworks are view centric, and developers organize their code based on pages. You'll probably go ahead and create a new view that represents a page. Of course, your view needs a controller and model, so you'll also create them. The problem with organization by pages is that there's little to no gain of reusability. Once you've created a page and you'd like to reuse only some parts of the page, you will need a way to encapsulate only a specific part of this model—the view and the controller.

UI components solve this problem nicely. I like to see them as a modular approach to MVC. Although they still embrace the MVC pattern, they also establish encapsulation and composability. This way, a view is a component itself, but it also consists of components. By composing views of components, one can gain a maximum amount of reusability:

UI components embrace MVC, but they also support encapsulation and composition on a much lower level

Technically, there are some challenges when implementing components with web technologies. JavaScript was always flexible enough to implement different patterns and paradigms. Working with encapsulation and composition isn't an issue at all, and the controlling part and the model of components can easily be implemented. Approaches, such as the revealing module pattern, namespaces, prototypes, or the recent ECMAScript 6 modules, provide all the tools that are needed from the JavaScript side.

However, for the view part of our components, we face some limitations. Although HTML supports great flexibility in terms of composability because the DOM tree is nothing else than a big composition, we have no way to reuse these compositions. We can only create one large composition, which is the page itself. HTML being only the final view that was delivered from the server, this was never really a real concern. Today's applications are much more demanding, and we need to have a fully-encapsulated component running in the browser, which also consists of a partial view.

We face the same problem with CSS. There is no real modularization and encapsulation while writing CSS, and we need to use namespaces and prefixes in order to segregate our CSS styles. Still, the whole cascading nature of CSS can easily destroy all encapsulation that we try to bring in place using CSS structuring patterns.

Time for new standards

Web standards have been evolving immensely in the last couple of years. There are so many new standards, and the browser became such a big multimedia framework, that it's hard for other platforms to compete with this.

I'd even go as far as to say that web technology will actually replace other frameworks in the future, and it probably will be renamed to multimedia technology or something similar. There's no reason why we need to use different native frameworks to create user interfaces and presentations. Web technologies embed so many features that it's hard to find a reason not to use them for any kind of application. Just look at the Firefox OS or the Chrome OS, which are designed to run with web technologies. I think it's only a matter of time until more operating systems and embedded devices make use of web technologies to implement their software. This is why I believe that at some point it will be questionable whether the term web technologies is still appropriate or whether we should replace it with a more general term.

Although we usually just see new features appear in browsers, there is a very open and long-winded standardization process behind them. It's very important to standardize features, but this takes a lot of time, especially when people disagree about different approaches to solving problems.

Coming back to the concept of components, this is something where we really need support from web standards to break the current limitations. Fortunately, the W3C (World Wide Web Consortium) thought the same, and a group of developers started to work on specifications under the hood of an umbrella specification called web components.

The following topics will give you a brief overview over two specifications that also play a role in Angular components. One of Angular's core strengths is that it acts more like a superset of web standards rather than being a complete isolated framework.

Shadow DOM

This part of the web components specification was the missing piece to create proper DOM encapsulation and composition. With shadow DOM, we can create isolated parts of the DOM that are protected against regular DOM operations from the outside. Also, CSS will not reach into shadow DOM automatically, and we can create local CSS within our component.

If you add a style tag inside shadow DOM, the styles are scoped to the root within the shadow DOM, and they will not leak outside. This enables a very strong encapsulation for CSS.

Content insertion points make it easy to control content from the outside of a shadow DOM component, and they provide some kind of an interface to pass in content.

At the time of writing this book, shadow DOM is supported by most browsers, although it still needs to be enabled in Firefox.

Angular's component architecture

For me, the concept of directives from the first version of Angular changed the game in frontend UI frameworks. This was the first time that I felt that there was a simple yet powerful concept that allowed the creation of reusable UI components. Directives could communicate with DOM events or messaging services. They allowed you to follow the principle of composition, and you could nest directives and create larger directives that solely consisted of smaller directives arranged together. Actually, directives were a very nice implementation of components for the browser.

In this section, we'll look into the component-based architecture of Angular and how the things we've learned about components will fit into Angular.

Everything is a component

As an early adopter of Angular and while talking to other people about it, I got frequently asked what the biggest difference is to the first version. My answer to this question was always the same. Everything is a component:

Within the Angular architecture, a component is a directive with an additional view

For me, this paradigm shift was the most relevant change that both simplified and enriched the framework. Of course, there are a lot of other changes with Angular. However, as an advocate of component-based user interfaces, I've found that this change is the most interesting one. Of course, this change also came with a lot of architectural changes.

Angular supports the idea of looking at the user interface holistically and fosters composition with components. However, the biggest difference to its first version is that now, your pages are no longer global views; they are simply components that are assembled from other components. If you've been following this chapter, you'll notice that this is exactly what a holistic approach to user interfaces demands. No more pages, but systems of components.

Angular still uses the concept of directives, although directives are now really what the name suggests. They are orders for the browser to attach a given behavior to an element. Components are a special kind of directive that come with a view.

Angular NgModule

Organizing an application solely by composing components comes with some challenges. Angular supports the concept of application modules, which essentially are just containers around components that help structure your application.

The concept of NgModule was introduced to mainly solve the following issues:

Explicit template parsing

: With the use of modules and by declaring all components, directives, pipes, and providers which are used inside of your application module, Angular is able to parse HTML templates very explicitly. This is really helpful when it comes to debugging. Let's say you're including an element within one of your component templates which does not match any of the selectors specified by the components within your module. Angular can now assert an error because you explicitly told it what components are available within your module. Without telling Angular which components belong to your application module, it would not be able to know if you're including a non-existing component within your template.

Simpler dependency resolution

: Since Angular can now simply resolve your main application module to find out what components are present within your application, things get simplified a lot. Imagine you have a very complex application existing of hundreds of components. Without modules,

Angular

would need to follow each individual component to find out how they are dependent on each other. With modules, Angular can simply check what components are declared inside of the module to find all components.

Lazy loading with the Angular router

: The router of Angular is able to load parts of your application lazily when required. This is a very powerful feature, but it requires that you declare a bundle of application artefacts like components or directives, to be loaded asynchronously after your main application has started.

NgModule

comes in very handy at this point. By creating a separate module using

NgModule

, you can now define a part of your application consisting of new components and other artefacts. Within the build of your application, this module is then built separately into its own JavaScript resource, which can be loaded asynchronously at runtime by the router.

Your application requires at least one main module, which is declaring all your application components. Let's look at a very simple example and build the main module for our HelloWorld component:

import {BrowserModule} from '@angular/platform-browser';import {NgModule} from '@angular/core';import {HelloWorldComponent} from './hello-world.component';import {ShoutOutComponent} from './shout-out.component';@NgModule({ declarations: [HelloWorldComponent, ShoutOutComponent], imports: [BrowserModule], bootstrap: [HelloWorldComponent]})export class HelloWorldAppModule { }

Similar to a component definition, we're using an ES6 class and a decorator to define an Angular module. The NgModule decorator of our main application module has three configuration properties:

A module dependency tree: Module A importing module B and C so that all components are available to module A

The declarations property is used to tell Angular what components, directives, and pipes are present within this module. If our application consists of 30 components, we need to add them all to the declarations of the NgModule. Every time you create a new component, you will also need to add it to the declarations array within your application module.

Within the array of the imports property, we can tell Angular to import other NgModule. This way, you can compose your application modules from many smaller modules if you like. However, there's no real benefit of structuring your application into submodules, unless you're exporting a submodule as a library, or if you're using the lazy loading feature of the router, as discussed earlier. It's crucial that you always import the Angular BrowserModule within your main application module. The BrowserModule contains all the Angular core components, directives, and other dependencies which are required in order to run your application within a browser environment.

Finally, the bootstrap property is telling Angular which of your components should be rendered first. You should specify your main application component here, which is representing the root component of your application. In the second chapter of this book, we'll take a closer look at the bootstrapping mechanism of Angular.

JavaScript of the future

It was not so long ago that somebody asked me whether we should really use the bind function of ECMAScript 5.1, as then we'd probably run into browser compatibility issues. The web moves very fast, and we need to keep up the pace. We can't write code that does not use the latest features, even if this would cause issues in old browsers.

The fantastic people from TC39, the technical committee that is responsible for writing the ECMAScript specification, have done a great job progressively enhancing the JavaScript language. This, and the fact that JavaScript is so flexible, allows us to use so-called polyfills and shims to make our code run in older browsers.

ECMAScript 6 (also referred to as ECMAScript 2015) was published in June 2015, exactly four years after its predecessor. There is a massive amount of new API additions as well as a whole bunch of new language features. The language features are syntactic sugar, and ECMAScript 6 can be transpiled to its previous version where it runs perfectly in older browsers. At the time of writing this book, none of the current browser versions have fully implemented ECMAScript 6, but there's absolutely no reason not to use it for production applications.

Syntactic sugar is a design approach where we evolve a programming language without breaking backwards compatibility. This allows language designers to come up with new syntax, which enriches developer experience but does not break the web. Every new feature needs to be translatable to the old syntax. This way, so-called transpilers can be used to convert code to older versions.

I speak JavaScript, translate, please!

While compilers compile from a higher-level language to a lower-level language, a transpiler or transcompiler acts more like a converter. It is a source-to-source compiler that translates code to run in a different interpreter.

Recently, there's been a real battle among new languages that are transpiled to JavaScript and can run in the browser. I used Google Dart for quite some time, and I must admit, I really loved the language features. The problem with nonstandardized languages is that they depend heavily on community adoption and the hype. Also, it's almost certain that they will never run natively within the browser. This is also the reason why I prefer standard JavaScript, and the JavaScript of the future using transpilers and polyfills.

Some people argue that transpilers introduce code that isn't very performant and, therefore, recommend that you do not use ECMAScript 6 and transpilers at all. I don't agree with this for many reasons. Usually, this is about performance in micro or even nanosecond areas where this often really does not matter for most applications.

I don't mean that performance doesn't matter, but performance always needs to be discussed within a context. If you're trying to optimize a loop within your application by reducing processing time from 10 microseconds to five microseconds where you'd never iterate over more than 100 items, then you're probably spending your time on the wrong things.

Also, a very important fact is that transpiled code is designed by people who understand micro performance optimization much better than I do, and I'm sure their code runs faster than mine. On top of this, a transpiler is probably also the right place where you'd want to do performance optimization because this code is automatically generated and you don't lose maintainability of your code through performance quirks.

I'd like to quote Donald Knuth here and say that premature optimization is the root of all evil. I really recommend that you read his paper on this topic (Donald Knuth, December 1974, Structured Programming with go to Statements). Just because the goto statements got banished from all modern programming languages, it doesn't mean this is less of a good read.

Later on in this chapter, you'll learn about tools that help you use transpilers easily within your project, and we'll take a look at the decisions and directions Angular went with regarding their source code.

Let's look at a few language features that come with ECMAScript 6 and make our life much easier.

Modules

Modules provide a way to encapsulate your code and create privacy. In object-oriented languages, we usually use classes for this. However, I actually believe that this is an anti-pattern rather than a good practice. Classes should be used where inheritance is desired and not just to structure your code.