left-icon

Angular Succinctly®
by Joseph D. Booth

Previous
Chapter

of
A
A
A

CHAPTER 1

Introduction

Introduction


Imagine, if you will, doing web development in an environment where you can control every aspect of the page you are building, and customize it to your heart’s content. Don’t like the white background on your page? You can change it easily using CSS. Want to react when your user moves into a field? You can hook into that event. It is a powerful environment—you develop your content and can leave its presentation as is, or customize it as much as desired.

CSS styling

For example, the following line of CSS sets your document to an antique white background with a navy font color.

Code Listing 1

            body {

                background-color: antiquewhite;

              color: navy;

            }

It’s powerful, quick, and easy!

JavaScript coding

You can hook into the event system just as easily by attaching event handlers to your elements.

Code Listing 2

<button id="btn" onclick="ShowBtn();">Hello World!</button>

Then, you add code to perform whatever function you like.

Code Listing 3

            function ShowBtn() {

                theBtn = document.getElementById("btn").textContent;               

                alert(theBtn);

            }

Third-party libraries

Once you start working in this environment, you begin to realize there are subtle differences between CSS and JavaScript, depending on the browser the user is running. One approach is to attempt to code around these differences, but that adds more complexity to this environment. Fortunately, there are third-party libraries that hide the complexity from you by handling the browser differences internally.

So, to keep focused on your application, rather than browser differences, you come to rely on third-party software libraries like jQuery, Knockout, and Kendo UI.

The good

These third-party libraries hide this complexity and provide great functionality to make development much easier. For example, we can use jQuery’s on() function to hide the browser differences in event handling.

The bad

However, these third-party libraries have access to the very same elements on the page that you do. So your nice page with the antique white background might be changed to a dark color background because a library replaced your CSS class name with its own. Oh, and that JavaScript code you wrote for when the button gets clicked? Well, it is possible a third-party library likes the function name ShowBtn(), so its method gets called instead of yours.

There are workarounds that most web developers are familiar with, such as loading libraries in a particular order, adding qualifiers to all your class names and function calls, and loading your CSS and JavaScript last. Some even go as far as not relying on third-party libraries.

Why AngularJS?

AngularJS is an open-source JavaScript framework developed and maintained by Google, Inc. and several open-source contributors. It was originally released in 2009, primarily aimed at making the HTML syntax more capable for application development. It included concepts such as data binding and HTML templates. In its simplest form, an AngularJS application would consist of an HTML page (with embedded “variables”) and a JavaScript object (called a controller) with properties and methods. The developer would manipulate the controller properties, and Angular would update the DOM (HTML page) to reflect the changing values.

Angular 2 was released in 2014 and completely rewritten to take advantage of new features that allow the development of components. It is a different approach to front-end development; instead of building a page and hoping your third-party libraries don’t conflict with your own code, you build components that will work the way you’d expect, and then use Angular to display the components to your user.

As we work through the book, we will develop components and use existing components to build our webpages. As Angular continues to develop, you will see many third-party components that can be used in an Angular application. This will allow us to do front-end web development much like other environments, selecting the components we want to use and tying them together into an integrated product.

Angular 2

Angular 2 is a complete rewrite of the Angular library, and is not backwards compatible with Angular 1 applications. This caused some concern among developers, but the Angular team wanted to take advantage of many new features that were not around in 2009. Angular 2 was about making the most of new browser developments to move forward and create better applications.

Some of the new web features that Angular embraces are:

ECMAScript

ECMAScript is a scripting language specification standardized by ECMA International. JavaScript is one of the most popular implementations of ECMAScript for client-side web applications. It was first published in 1997, and has grown over the years. The most recent version (ECMAScript 2018) adds substantial syntax improvements for writing complex scripting applications. While not every browser supports all the new features, ECMAScript is the future of JavaScript.

Note: You can read about ECMAScript 6 in Matthew Duffield’s book ECMAScript 6 Succinctly, available from Syncfusion. Although not the current version, it’s a good source for understanding the standard.

TypeScript

TypeScript is a superset of JavaScript developed and maintained by Microsoft. It adds features to JavaScript, most notably data types for variables. It also adds many of the features in ECMAScript (the scripting language most current browsers support). Angular itself is written in TypeScript.

TypeScript files (.ts extension) are transpiled (meaning source code is converted to another source language) into JavaScript files (.js extension). This allows developers to use the features of TypeScript and still have browsers support and run the script.

We will use TypeScript in this book’s examples, but it’s okay if you are not familiar with the language. Knowing JavaScript and any object-oriented language (such as C#) will allow you to feel right at home with TypeScript. (Plus, Syncfusion has a book in the Succinctly series to help you learn it if needed.)

Dependency injection

Dependency injection is a software design pattern that attempts to reduce tightly coupled components by changing how component dependencies are handled. For example, if a logging component needs to notify users when something is amiss, it might be tempting to access another component (NotifyUsersByEMail, perhaps) within the logging component. While coding is a bit simpler, it creates a dependent relationship between the logging and the NotifyUsersByEMail component.

These dependencies make it difficult to test and debug components individually. For example, if you expect an event to be logged and users to be notified but it doesn’t happen, you need to determine if the mail component failed or the log component failed. Also, if the mail component changes, then the logging component must be updated to accommodate the changes.

A common approach to solving this is to write an interface that describes how the logging component plans to interact with the notification tasks it needs. Namely, it defines how to specify users, the subject and message, and how to invoke the send method. The logging component doesn’t know the details, just that it can access another object that matches the interface. The object itself gets passed into the component (often from the constructor) for the base component to use. The logging object doesn’t care about the particulars of the object, only that it has the agreed upon fields and methods.

Such an approach makes testing easier and accommodates changes as well. For example, if we wrote a NotifyUsersBySMS object, as long as it offers the same methods the Logging component expects, we can change the notification behavior simply by passing in a different component to the constructor.

Angular versions

Angular is a constantly evolving and improving framework. The current version of the framework is 7.0. In general, new major releases are planned every six months and the new release is backward compatible with the last major release. When possible, you should update to the new major release fairly soon after it is stable.

Versioning

The Angular version number consists of a major, a minor, and a patch number. Major releases (every six months) contain significant new features, and you will likely need some code refactoring and update scripts to use the new release.

Minor releases contain smaller features that are almost always backward compatible. You can likely use the release without code refactoring, but should explore the features to see ways to improve your application.

Patch releases are usually bug fixes, and very low risk, meaning they are very unlikely to break your application.

This website is a good resource for staying current with the Angular release schedule. You can also follow @angular on Twitter or subscribe to the Angular blog.

At the time of writing, Angular 7.0 is the current version.

Web components

Web components were first introduced in 2011, although components were a part of software development for many years prior to that. The standards necessary to implement web components are being worked on by the W3C, and they represent the future of web application development.

Without web components

When you develop front-end code, you are generally using some JavaScript framework, and possibly some CSS, sprinkling it throughout your HTML, and hoping that some subsequent CSS or JavaScript files don’t come along and change all the code you’ve written.

Recently while working on a website, I found a JavaScript library that looked like it provided a solution to an issue. I added the library and the CSS files to my layout page, and got the functionality I wanted, with one nasty little side effect: the CSS changed all my <p> tags to be text-align: center.

Front-end development becomes a matter of carefully combining JavaScript and CSS libraries that hopefully don’t conflict with each other and produce the functionality we are trying to implement.

Web components

Web components are essentially fully encapsulated HTML elements that the browser knows how to display. Since the HTML and CSS are encapsulated in the component, the component will always display the way it was designed, even if some later-loaded CSS style sheet changes the presentation rules on HTML elements.

When you create an HTML page, you are defining the Document Object Model (DOM). The DOM is a representation of your HTML (or XML, etc.) source code as a nested tree structure. Browsers use various layout engines (such as WebKit or Gecko) to handle parsing the HTML into a DOM. Once the DOM is built, JavaScript and CSS can manipulate the DOM. If you’ve worked with jQuery or CSS, you’ve certainly seen selectors such as # (ID) or . (class) to get particular DOM elements.

Shadow DOM

The Shadow DOM is an encapsulated DOM object that can be created from any existing DOM element. The DOM element that creates the Shadow DOM is known as the ShadowHost. The new element is referred to as the ShadowRoot. The following JavaScript fragment shows how to create a Shadow DOM element.

Code Listing 4

        <script>

            var ShadowHost = document.querySelector('button');

            var ShadowRoot = ShadowHost.createShadowRoot();

                ShadowRoot.innerHTML="Hello from Angular";

        </script>

Markup in the Shadow Root is not visible to the scripts outside of the Shadow DOM. The purpose of the Shadow DOM is to provide an encapsulated snippet, safe from prying eyes.

If you explore the following example in Code Listing 5, you see that the HTML element contains Hello, world. However, the script creates a ShadowRoot (if it does not yet exist) and sets the innerHTML to "Hello from Angular". When the browser executes this code, the button’s inner content gets replaced with whatever content is in the ShadowRoot.

Code Listing 5

    <body>

        <button id="btn" onclick="ShowBtn();" >Hello, world!</button>

        <script>

            var ShadowHost = document.querySelector('button');

if (ShadowHost.shadowRoot==null)                          

                 {   

                      var ShadowRoot = ShadowHost.createShadowRoot();

                     ShadowRoot.innerHTML="Hello from Angular";

                 }

        </script>

        <script>

            function ShowBtn() {

                theBtn = document.getElementById("btn").innerHTML;               

                alert(theBtn);

            }

        </script>

    </body>

However, when you click the button, the ShowBtn() function shows the content Hello, world, not the content that the browser displayed from the ShadowRoot. This is an example of the encapsulation and scoping necessary to build web components.

Note: Some browsers expose parts of the Shadow DOM to CSS through special pseudo-selectors. Also, component authors can choose to expose some content, particularly theming and styling.

Template tag

Another piece of the component puzzle is the HTML <template> tag. This tag allows us to build HTML fragments for later use. Content inside a template tag will not display, and is not active (images won’t be downloaded, scripts won’t run, etc.).

Templates can contain HTML, CSS, and even JavaScript. They can be placed anywhere with the DOM and stay inactive until you need them. The following is a simple template that draws a border and shadow around an <h3> element and adds some text.

Code Listing 6

        <template>

            <style>

                h3 {

                    color: darkblue;

                    border:2px solid gray;

                    box-shadow: 10px 10px 5px #0f0f0f;

                    width:20%;

                    margin-left:20px;

                    padding-left:10px;

                    }

            </style>

            <h3>From the Shadows… </h3>

        </template>

Now, when we create our Shadow Root, rather than rely on manipulating the innerHTML property, we will plug the template code in. The <h3> style within our template, since it is in the Shadow Root, will not impact any other <h3> styling the page might be using.

Code Listing 7

var ShadowHost = document.getElementById('HostDiv');  

if (ShadowHost.shadowRoot==null) // See if the element has a shadow root?

   {

      var ShadowRoot = ShadowHost.createShadowRoot();  

      // Get the template                         

      var tmpl = document.querySelector('template');

      ShadowRoot.appendChild(document.importNode(tmpl.content, true));

    }

We grab the template element (we can use getElementById() if we have a number of different templates) and append it into the ShadowRoot element. Our screen will now show the following in the HostDiv element.

Shadow Root

Figure 1: Shadow Root

Getting content from the host

Often, our template code will want to get its content from the host element, rather than hard-coding the content in the template code. For example, if our ShadowHost element looked like the following:

Code Listing 8

<div id="HostDiv"><span>The DIV</span></div>

We could replace our template’s HTML line:

Code Listing 9

<h3>From the Shadows… </h3>

with the following fragment:

Code Listing 10

<h3>Courtesy of the shadow host <content select="span"></content></h3>

When the template is inserted, it will grab the content of the ShadowHost’s <span> tag and use it instead.

Content from Shadow Host

Figure 2: Content from Shadow Host

Taken together, the Shadow DOM and the template system open the door to allow components within the front-end development of webpages. And that is one of the biggest benefits Angular provides.

Summary

Angular takes advantage of web components and the Shadow DOM to support component-driven development. In the rest of the book, we will use the Angular framework to create a component-driven application, and perhaps along the way, create some reusable components for other applications.

Note: The code samples in this book are available for download here.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.