Angular Starter Project with Basic Routing & System.js

Angular

Angular logo - routing An Angular starter project with basic routing, System.js as the loader and a local Express.js web server.

Starting an Angular project from scratch can be tedious, but the Github repo links at the end of this post provide a starting point that you can easily clone, edit and shape as needed, and should save you some work. An important note: this project is built using System.js, and in this approach, the Typescript code is compiled on the fly. This starter project is not recommended for production application, but just to provide a quick and easy way to spin-up an Angular application for local testing. You can also accomplish this using the Angular CLI, but I wanted to offer another option.

Note, also, that when you clone the code from GitHub, there is a local web server provided. This server allows you to make true HTTP requests from the local web page (i.e. you don’t want to load this code into your browser using the file:/// protocol; that simply won’t work). And just be aware that the Angular CLI is usually an even quicker and easier way to spin-up an Angular application for local testing.

Example # 1

In Example # 1, we have app.module.ts. Note the RouteXComponent references (i.e. “Route1Component“, “Route2Component” and “Route3Component“). These are the components that make up the application and that need to be defined as routes. There’s not too much more to discuss here; this code exists simply to boot up the application.

Example # 2

In Example # 2, we have routes.ts, which is where the routing is configured. Right now, the routes are route1, route2, and route3, and they will instantiate the “Route1Component“, “Route2Component” and “Route3Component” components accordingly. You can change them as needed for your project, you’ll just need to rename each component, and its associated files.

Now take a close look at line # 8. This line tells the router what to do when a specific route is not selected (i.e. when the user requests the root of the application: “/”). So, here we are saying to the router: when the user browses to the root of the application, take them to route1.

Example # 3 – A

Example # 3 – B

In Example # 3, we have our Route1Component component. The other components are identical, and they’re named accordingly. To use this for your project, just rename the route1 references to whatever you want to call your component. And this change would need to be made in app.module.ts, routes.ts and then each route. These routes do not do too much, as you can see in Example # 3 – A and Example # 3 – B. They’re just meant to provide an empty shell that you can use to quickly spin-up a local test Angular application. The easiest way to do this is to clone the code in github, run npm install, and then npm start.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-routing-basic

How do I use the Angular ngModel directive?

Angular

Angular logo -routing

The ngModel directive creates a two-way data binding between an HTML form element and the component.

In the most recent version of Angular, data binding is one-way by default. Notably, this is one of the key improvements over Angular 1.x in that it eliminates unnecessary performance issues that can crop up quickly. But the beauty of the ngModel directive is that it provides a way to explicitly give your template and your component’s data a two-way binding. So, when it is changed on one end, it is updated on the other. In other words, your data becomes “live”.

Now the most common case for two-way data binding is HTML forms. Here, as the user makes changes to a form, you want to capture those changes in your data. And conversely, you’ll also want any changes in your data to be reflected in the form. And here’s where Angular’s ngModel directive comes in; it’s the key to this live relationship. You simply assign a data point from your component to this directive in your template and your binding becomes two way. Take a look at the examples below, for further examination.

Example # 1

In Example # 1, we have our component. There are two properties: content and title. These properties will be connected to our form input elements via the ngModel directive. This two-way data-binding means that when the property is changed in one place, it is updated any place else that it is referenced, and vice verse.

Example # 2

In Example # 2, we have our Angular template. There is a text-input element and a textarea element. The text-input element has an ngModel directive and its value is: title. This means that two-way data binding is set up for the title property. The textarea element has an ngModel directive and its value is: content. This means that two-way data binding is set up for the content property.

Below the input elements is a div element with two placeholders: {{title}} and {{content}}. The net result of this is that when you enter any text in the text input, that text will update the {{title}} placeholder in the UI. Also, when you enter any text in the textarea, that text will update the {{content}} placeholder in the UI

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: github.com/kevinchisholm/video-code-examples/tree/master/angular/templates-and-data/ngModel

Summary

So, Angular’s default one-way data binding methodology is a key benefit of its 2+ upgrade. And, of course, in most cases, this approach is sufficient. But, as it turns out, in some cases, such as HTML forms, you want a “live” connection between your form and your data source. So this is where ngModel directive comes in. It provides the “live” connection otherwise known as two-way data binding.

An Introduction to Angular Reactive Forms

Angular

angular reactive formsAngular reactive forms provide a model-driven way to build, manage and test your HTML forms. There is also a difference when it comes to setting up event handlers.

In this article, I’ll provide an introduction to Angular Reactive Forms. You’ll learn how to create model-driven forms using the FormBuilder, FormControl and FormGroup modules. This is a high-level explanation and will primarily focus on how to compose forms using these modules, and how reactive forms differ from template-driven forms. Now you may have found that the term “model-driven forms” is often used to describe the same topic, but “reactive forms” seems to be the terminology that Angular uses consistently, so we’ll stick with that.

Angular’s reactive forms provide a way to build and interact with your forms in a more programatic way. Now, some may get the impression that reactive forms differ from template forms in that you don’t need to create the template, but this is incorrect; you do need to create it. With reactive forms, however, you build a matching model in your component that provides programmatic access to your form. This is significant in two ways: first, your form is now testable; second, your template is less tightly coupled and you can move your business logic to your component, or better yet, to your service.

Differences between Template Driven and Reactive Forms

With template-driven forms, your validation logic lives in the template. Now this is fine if your validation is simple (e.g. “required” or “min-length”), but once your validation logic involves any level of complexity (and when is this not the case : – ), then your template becomes bloated and difficult to read. With reactive forms, your validation logic lives in your component, or it can be proxied to your service. In either case, this is a better approach. Also, with template-driven forms, the only way to check the form is an end-to-end test. Now there’s nothing wrong with E2E tests, but that should be a final layer of defense. The real hardened testing should come via your unit tests, and with reactive forms, this is exactly the approach you can take.

Using FormControl – Example # A – 1

The Change Event Using FormControl – Example # A – 2

The Template Using FormControl – Example # A – 3

VIEW THE FULL CONTENTS OF THIS HTML FILE HERE: https://gist.github.com/kevinchisholm/cfbc4005e0ce7041553f35e6b35a6314#file-home-a-html

Example A contains the component and template for a fairly basic reactive form, but let’s look at Example A-1 first. Notice that I’ve imported FormControl and FormGroup from @angular/forms. These are the ones I’ll need in order to start building our form. Line # 10 is interesting because I’ve added a registerForm property, but just notice this property type, which is FormGroup. So here I’m saying that my registerForm property will be an instance of the FormGroup class. In fact, on Line # 14 that’s just what happens: I instantiate that class: this.registerForm = new FormGroup({…}), and when instantiating the FormGroup class, I pass it an object. In this object, I’ve created seven instances of the FormControl class, and at this point, I’ve done two things: I’ve created an instance of FormGroup, and I’ve passed several instances of FormControl to that constructor. So, what this comes down to is that I have a form “group” and a bunch of form “controls.”

On Line # 24, I have another interesting thing going on, which is a subscription to an Observable: this.registerForm.valueChanges.subscribe. Note that this is a major departure from template-driven Angular forms. My form is now a source of continuous values that I can subscribe to. I’ve passed an anonymous function to the valueChanges.subscribe method, this anonymous function receives an object as its first argument, and that object is a data-driven representation of my form. Essentially, this data contains all of the values for all of the fields in my form. Notice that on Line # 28 I’ve included a console.dir() statement, which allows me to inspect that data that I receive each time my subscription to the form gets an update. Now if you look at Example A-2, you’ll see the contents of this data. Notice that all of the property names match the names of the FormControl instances that I created on Lines 15-21. In Example A-3, you see the actual form template, which is not all that interesting, but there are a couple of things to keep in mind. First, the template is very simple, which is an improvement over the template-driven approach to forms. Second, the form itself has a [formGroup] attribute which matches the registerForm property from my component. Also, each form control has a formControlName attribute that corresponds to a FormControl instance from my registerForm property (which is an instance of the FormGroup class).

Using FormBuilder – Example # B – 1

The Change Event Using FormBuilder – Example # B – 1

The Template Using FormBuilder – Example # B – 3

VIEW THE FULL CONTENTS OF THIS HTML FILE HERE: https://gist.github.com/kevinchisholm/cfbc4005e0ce7041553f35e6b35a6314#file-home-b-html

In Example B I have an alternative approach to my home component. I’ve imported the FormBuilder component, and on Line # 15, instead of instantiating the FormBuilder class, I call a static method of that class named: group(). Things look a little different when compared to the previous example of this component. I pass an object to the static group() method, but instead of providing instances of the FormControl class, I pass property names that match my actual form controls in the template. This, then, enables me to avoid the numerous instantiations of the FormControl class, which, in turn, makes for more concise / readable code.

Notice that on Line # 20, I assign to the address property another call to the static group() method. I’m effectively creating a nested form group, and there are a couple of real wins here. First, the syntax is so simple: I create properties, which are form controls, and then when I want to logically group some form controls, I make a call to the static group() method, passing it yet another configuration object. In this case, the logical grouping is the address, which makes sense. Note that the street, city and zip code fields are all part of an address.

At this point, you may be wondering why the values for some of the form group’s properties are strings, yet some are arrays. Well, this is one of the real benefits of the reactive form syntax. That is, when you provide an empty string, the form control’s initial value is blank. When you provide an array, the first array element is the initial value of the control, and the remaining elements are the control’s validators. In the case of firstname and lastname, both controls are made mandatory via the validators.required built-in validator. For street, zip and city, assigning an empty array tells Angular that the initial value is blank and there are no validators. In other words, an empty array is a valid assignment, but it does not provide much value. So, I could have simply provided an empty string.

On Line # 27, I’ve set up another subscription to the registerForm.valueChanges observable. So, when you look at Example B-1, you’ll notice that the data object that is passed to the subscription callback has an address property, which is an object. This address object has properties for street, zip and city. So, by creating a nested FormControl instance, I’ve created an object with another object as one of its properties

In Example B-3, you’ll see the template for this form. Notice the section with the class name “form-data-container,” which is for demonstration purposes. If you clone the Github repo for this project and run it locally, you’ll see that any values you enter into the form fields will appear in the “form-data-container” section of the UI. The main purpose for this is to demonstrate that the entire form can be represented by a data object, which can then be used to update the UI in some manner.

Summary

Angular Reactive Forms is a major improvement over the Angular 1.x way of doing things. Angular template-driven forms are a continuation of the approach taken in Angular 1.x. So, while the template-driven forms approach can be a bit easier when it comes to creating a simple form, that simplicity is quickly compromised if your form and / or validation logic increases beyond a certain point. The Reactive Forms approach requires a little more up-front effort, but the reward is quickly granted in the form of code that is testable, easier to read, and easier to manage.

Angular Child to Parent Communication with @output()

Angular

Angular Logo - @output()When passing data up to a parent component with the Angular @Output() decorator, you’ll need to set up an event handler in the parent, and then emit events from the child component whenever your data changes.

In the article: “Angular Child to Parent Communication with @ViewChild()”, I detailed two ways in which data can be passed from a child component to a parent component. In this article, I will cover the other approach, which leverages the @output() decorator.

When we walked through the steps for the @ViewChild() decorator, we saw that the majority of the setup work happens in the parent component. Here, with the @output() decorator, things are a bit different. For the most part, the required steps are spread out across the parent component, the parent template and the child components. I was actually a little surprised to see how intimate the relationship between the child and parent components / templates are. On a high level, the data communication starts with event handlers in the parent component. Then, in the parent component’s template, we specify event handlers for each property that we want to pass-up to the parent component. And finally, in the child component, there is a two-step process.

First, we use the @Output() decorator to create an instance of EventEmitter. Next, we set up methods in the child component that match the naming convention used in the parent component template (see Examples # 2 and # 3 below). It’s a surprisingly close relationship between the various pieces of the puzzle, given Angular’s declarative-focused syntax. Let’s take a look at some code examples.

Full Working Example Code

You can clone the full working example code here: https://github.com/kevinchisholm/video-code-examples

  1. Go to this folder in your terminal: angular/components/@output
  2. Follow the directions in the readme

The Parent Component – Example # 1

In Example # 1 we have the parent component. Here, the userName and userPhone properties will be utilized in Example # 2, to set up the binding for the data that we will receive from the child components. And on line #s 11 and 15, we create methods that become event handlers. Note here that although I name each method’s lone argument “$event”, this is completely arbitrary; I could have named it anything. The key thing here is that in each of these event handlers, we update the userName and userPhone properties with the data that we receive from the child components (i.e. $event).

The Parent Component Template – Example # 2

So now, in Example # 2 we have the parent component template. As expected, we see bindings for the userName and userPhone properties. But the interesting parts happen on line #s 5, 6, 9 and 10. We’ve set up handlers for the nameEvent and phoneEvent events, and the values that we assign to these handlers match up with the methods that were defined in the parent component: nameEventHander and phoneEventHander. So, this is where the connection is made between the child and parent components. In fact, the syntax used probably looks familiar to you: (click)=”someEventHandlerName($event)”. In our code, the difference is: instead of click, we are connecting a method to a custom event (i.e. nameEvent or phoneEvent).

The Child Components – Example # 3

In Example # 3 we have the child components, and on line #s 8 and 9 we have used the @Output() decorator to create two custom events. These events are instances of Angular EventEmitter, so the nameEvent and phoneEvent properties become event emitters. Then on line #s 14 and 18, we have the onNameChange and onPhoneChange methods. In these methods, we use the emit() method of the nameEvent and phoneEvent properties, which are instances of EventEmitter. So this, of course, is where the data is getting passed up to the parent component.

The Child Component Templates – Example # 4

In Example # 4 you’ll see the code for both of the child component templates. Notice how we have set up an event handler for each text input keyup event. This is where we are assigning the onNameChange and onPhoneChange methods to those events. So what happens is: the user enters some text in either of the inputs, which triggers the onNameChange and onPhoneChange methods, which in-turn emit the custom events. That triggers the handlers in the parent component’s template, passing up the data from the child.

Summary

So, in leveraging the @output() decorator, keep in mind that while the differences between it and the @ViewChild() decorator are not minor, they’re also not particularly complicated, once you understand how the data communication channels are set up. This means that when you use the Angular @output() decorator, you will be adding an event handler to your parent component. That event handler will then receive data, which will allow you to update the parent component’s template with that updated data. You will also be configuring the event handler on the child component HTML element in the parent component’s template, which is where the data connection happens. And then finally, in the child component, you’ll leverage the @output() decorator to emit an event with updated data, thus allowing the data to flow up to the parent component.

Angular Child to Parent Communication with @ViewChild()

Angular

Angular Logo - ViewChild()Angular child-to-parent communication with the @ViewChild() decorator mostly involves configuring the parent component to pay attention to one or more child component properties.

In the article: “Angular Parent to Child Communication with @Input()”, I covered the process of passing data from a parent component to a child component. I this article, I will cover one of two possible approaches to Angular child-to-parent communication. This particular approach takes advantage of the ViewChild decorator, and the syntax is fairly straightforward and easy to understand.

When I first looked into Angular child-to-parent communication, I assumed that it might be as simple as reversing the steps taken with the @ViewChild() decorator, but this was not quite the case. Leveraging the @ViewChild() decorator differs from the @Input() approach because not only are we accomplishing the opposite task, but the overall steps and methods of communication lack resemblance to the @Input() approach. Also, the communication mechanism requires a bit of event handling.

First, we import the child component from the parent component. The @ViewChild decorator is then used to set up a new property on the parent component, which provides the data connection from the child component. Next, we tap into the ngAfterViewInit component lifecycle hook, thereby making the live connection between one or more parent component properties and the respective child component properties. The steps required in the child component do not require much special attention, so it’s safe to say that Angular child-to-parent communication with the @ViewChild() decorator mostly involves configuring the parent component to pay attention to one or more child component properties.

Full Working Example Code

You can clone the full working example code here: github.com/kevinchisholm/video-code-examples/tree/master/angular/components/ViewChild

  1. Go to this folder in your terminal: angular/components/ViewChild
  2. Follow the directions in the readme

The Parent Component & @ViewChild() – Example # 1

Example # 1 contains all of the code for the parent component. On line #s 2 and 3, we import the children components: Child1Component and Child2Component. Now this is a bit of a departure in that we normally import services in an Angular component, but in this case, we need access to the instances of the children components.

Next, on line #s 10 and 11, we use the @ViewChild decorator to create properties that represent instances of each child component class. The syntax is a bit odd, but just note that while we reference the child component class twice (e.g. Child1Component), what we wind up with is a new property (e.g. child1).

On line #s 13 and 18 we create the properties userInfo1 and userInfo2, and we do this to set up objects that can be used to take in data from the child components. Finally, on line # 23, we tap into the ngAfterViewInit component lifecycle hook, and what we are saying here is: “after the PARENT component has completely initialized, please get the child1.userInfo and child2.userInfo values and assign them to this.userInfo1 and this.userInfo2.

So, as I mentioned above, most of the action is now over. The real “wiring-up” steps take place in the parent component. The methodology here is that we are listening for changes to some data points on the child components.

The Parent Component’s Template – Example # 2

In Example # 2 we have the parent component’s template, and on line #s 3, 4, 7 and 8 we have bindings for the child component properties that we wired-up on the parent component. These are the places in the UI that the child component data will render (and automatically update whenever that data changes in the child). And then, on line #s 10 and 11, we have the child1 and child2 elements. Nothing too special there, since most of the setup work was done in the parent component.

The Child 1 & Child 2 Components – Example # 3

Example # 3 has the code for both the Child 1 and Child 2 components. The code is virtually identical, so I won’t spend any time comparing the two, but what I wanted to point out here is that there is not too much to point out : – ). The code you see in the Child 1 and Child 2 components pretty much looks like what you would expect from any Angular component. Just note, though, that in each child component, we create a userInfo object which is used to set up the data bindings.

The Child 1 & Child 2 Component Templates – Example # 4

And pretty much the same situation here; the Child 1 and Child 2 component templates are virtually identical. We have HTML text inputs that allow the user to enter some text, and whenever the user adds or edits that text, the respective properties of the userInfo object are updated and that data flows up to the parent component.

Summary

If you have the time, I recommend cloning the github repo at the top of this page and running the example code locally, because while (I hope) the code examples are straightforward, it might be helpful to actually see the code in action. When you do, you’ll see that as you type in each child component text input, that data is reflected in the parent component. This makes it a bit easier to understand how the data flows up from the child components to the parent component.

mapbox-gl Uncaught ReferenceError: t is not defined

Mapbox

JavaScript LogoMy Mapbox integration was working fine locally. But then when did a Webpack build and pushed the assets to my web server, there was a JavaScript console error

I was implementing Mapbox in an Angular 4 application and everything was going fine. I was working locally, but after getting some UI issues worked out, things seemed to be going very smoothly. But when I ran my build and then viewed the static assets remotely, I had this lovely little JavaScript error in my console: “Uncaught ReferenceError: t is not defined“.

Hmmmm. everything seemed just fine to me. I did some troubleshooting and the issue looked like it was being caused by Mapbox. How could this be? It was not a problem locally.

I found the answer here: Build fails when using mapbox-gl webpack 2 and UglifyJSPlugin #4359.

Credit really goes to zezhipeng  – whose answer was spot-on. Seems that when Webpack parses the mapbox-gl module, things do not go too well. So I just needed to add this line to my Webpack config:

(the “” is just whatever else you have in your module.exports.module object.)

And that was it, working again. Thanks zezhipeng!

Angular Parent to Child Communication with @Input()

Angular

Angular LogoThe Angular @Input() decorator provides a channel by which a parent component can communicate with its child.

I think most Angular developers would agree that more of those smaller components that do one thing and do it well make for more manageable code, and a critical part of this design pattern is the parent-child communication. This is because, with more of the smaller chunks of code, nesting components becomes unavoidable. So, in this article, I’ll demonstrate how you can leverage Angular’s @Input() decorator to allow your parent components to smoothly pass information down to a child.

On a high-level, the communication channel is composed of mainly two parts: First, you provide custom attributes in the template code for your child components and pass references to values that you want to pass down. Then, you use the @Input() decorator to accept that data in the child component. Now there are two ways to leverage the @Input() decorator in your child component, and I’ll cover each one. For now, let’s just look at some code examples to see how these two pieces of the puzzle fit together.

Full Working Example Code

You can clone the full working example code here: https://github.com/kevinchisholm/video-code-examples

The Parent Component – Example # 1

In Example # 1 you’ll see the code for the parent component. Okay, now let’s take a look at lines # 8 and 9, where we expose two properties: userName and userPhone. Now we’ll consume those two properties in Example # 2, but for now, just be aware that in order to pass data down to the child component, we need to expose that data as properties on the parent component class.

The Parent Component’s Template – Example # 2

So here in Example # 2 we have the parent component’s template, and on line #s 1 and 6 there are two HTML text inputs. What we want now, is for the user to enter some text into these inputs, and then that data will be passed down to the child component. Notice how the ngModel directives for the texts input are assigned to the userName and userPhone properties. Then on line #s 11 and 15, we have the two child components. In each case, we have added a custom attribute to the child component’s HTML element. Now notice that the userName and userPhone properties are provided as values for the child1 component. And for the child2, component we use “theUserName” and “thePhone“. Okay, let’s put that aside for now, and we’ll discuss it in Example # 5.

But why are the custom attributes named “userNameFromParent” and “userPhoneFromParent” ? Well, these names are arbitrary; we could have just as easily named them “foo” and “bar”. The important thing to keep in mind is: the “userNameFromParent” and “userPhoneFromParent” custom attributes set up the communication channel. In other words: the “userNameFromParent” and “userPhoneFromParent” custom attributes are the connection to the child component class, and the userName and userPhone properties are the bindings for that data. And because of the “{{ }}” bindings, any time the userName and userPhone properties change, the updated values will be passed to the child component via the “userNameFromParent” and “userPhoneFromParent” custom attributes.

The Child 1 Component – Example # 3

Example # 3 contains the code for the child component, so let’s jump right to line #s 7 & 8. The @Input() decorator is used to declare that userNameFromParent and userPhoneFromParent properties are not just any old properties; they are inputs from the parent component (in this case, we have initialized them as an empty string). This is an important relationship, since the “userNameFromParent” and “userPhoneFromParent” custom attributes of the child template are connected to these class properties that are decorated with @Input(). This is that “communication channel” we covered earlier.

Child 1 Component’s Template – Example # 4

In Example # 4 we have the child component’s template, where there are only two lines of code, so things are pretty simple. But notice the userNameFromParent and userPhoneFromParent bindings. Importantly, this is where the template is bound to the two properties that we created with the two @Input() decorators. So if you go ahead and clone the GitHub repo listed above and run the code locally, you’ll see that when you enter some text into the two inputs of the parent component, that data is passed down to the child component and rendered in the UI.

The Child 2 Component – Example # 5

In Example # 5 we have the child 2 component, which I wanted to revisit, so I could demonstrate the 2nd option for how to leverage the @Input() decorator. In this case, we can “alias” the data that is passed down from the parent component. In other words, we defined the two data points as “userNameFromParent” and “userPhoneFromParent” in the parent component, and in Example # 4 and # 5, we used those property names verbatim in our child component template bindings. But in this case we “alias” the data by passing a string to the @Input() decorator. So, instead of @Input() PROPERTY_NAME = “”, we use the following syntax: @Input(PROPERTY_NAME) alt_property_name = “”.

So here we are saying to Angular: “I want to consume theUserName and thePhone, but I want to call it something different in my child component”. So now we have two properties: name and phone. But remember back in Example # 2, where we mentioned that we would discuss theUserName and thePhone? Well, this is where I want to revisit that part of the parent template. In this child 2 component, we are consuming theUserName and thePhone, which were passed down from the parent template, but we are declaring two new properties: name and phone.

Child 2 Component’s Template – Example # 6

In Example # 6 we have the child 2 component’s template, and as you have probably guessed by now, this is where we are consuming the name and phone properties. When you run the working code in your browser, you’ll see that just as with the child 1 component, whatever you type in the text inputs will be rendered in this child 2 template. The difference is that we took a slightly different approach with the @Input() decorator, creating two new properties.

Summary

In this article, we learned how to use the Angular @Input() decorator to pass data from a parent component to a child component. We also learned how to set the custom attributes in the parent components’ template and bind values from the parent in order to set up the data flow. Then, we covered the @Input() decorator’s syntax, learning how to receive the data in the child component. And finally, we discussed the two ways of using the @Input() decorator so that you can have the option of aliasing the child component’s properties.

How do I detect a text-input change event with Angular?

Angular

Angular logo -routing
If you want to act upon the change event of a text input or text area, assign a method to the change attribute.

Okay, let’s start with the basics. Let’s say an HTML text input is simply sitting there, waiting for the user to click the form’s submit button, after which your JavaScript code would take that text input’s value and send it as part of the HTTP POST request. But what if you don’t want to wait; what if you want to know if the user has made a change to the text input. Let’s use form-validation as a typical case; let’s say you want to know if the user has entered a valid value. For example, you might want to enter an email address, a telephone number, or a social security number. Well, by assigning an event handler to the element’s (change) attribute, you’ll be able to act upon any change in the text input.

Let’s take a look at a couple of examples:

Example # 1

In Example #1 we have our component. We will consume the changeCount property in our template.

Example # 2

In Example # 2, we have our template. In the H3 tag, we use the {{changeCount}} placeholder to show the value of the changeCount property. The text input has a change attribute. For the value, we assign an expression: “changeCount = changeCount + 1”. This means that each time the change event fires on that text input, the changeCount property is incremented by one. Thus, each time the user makes a change to that text input, the UI message “You have made {{changeCount}} changes so far.” is updated and the {{changeCount}} placeholder  shows the current value of the changeCount property.

So, for the sake of simplicity, we have incremented the value of the changeCount property inline. That is, instead of assigning a method to the text input’s (change) attribute, we assign an expression. Now even though this approach is not a recommended pattern, it does have the advantage of being valid and easy to read. So the best approach is the normal one, which is to assign a method to the (change) attribute. And that method would be a property of our HomeComponent.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-change-attribute

How do I use the Angular ngFor Directive ?

Angular

Angular logo -routing

When you have an array of data to show in the page, ngFor does all the work. You simply define your UI element once, and ngFor takes care of the rest.

Creating a for loop is one of the first things every programmer learns. You set up your loop, and then define what should happen in each iteration of the loop. But while this may sound simple, it can create a lot of boilerplate code. Each time you need to set up an iteration, you need to create your counter variable (for example “var i = 0”). The thing is, this kind of repetitive code can quickly become tedious and difficult to manage. And since Angular takes care of DOM rendering for you, you actually don’t want to manually iterate data with the intention of rendering multiple DOM elements. So the better approach would be to let Angular do the heavy lifting when it comes to iterating data and rendering DOM elements based on that data.

When leveraging the Angular ngFor directive, the approach is very much the same. The number of iterations is determined by the length of your array, so Angular handles that for you. The only thing left to do is define your data and a variable that will represent the model on each iteration of the loop.

You’ll find that the approach here is somewhat similar to using a library such as underscore.js or lodash.js; you simply let the library take care of the tedious loop setup code. And Angular offers even more value here because it takes care of not only the data iteration, but the DOM rendering as well. In addition to this, Angular takes care of all the deep DOM management tasks such as hiding & showing, data binding and event handler binding. So let’s face it, that makes for a much more streamlined process and saves you a great deal of work!

Example # 1

In Example # 1, we have our component. Take note of the days property. It contains the seven days of the week. This is the data which we will use in our template.

Example # 2

In Example # 2, we have our template, containing an unordered list. Our goal is to have a list item for each day of the week. Instead of manually creating seven list items, we have only one. This single list item has an ngFor attribute. The value assigned to this attribute is: “let day of days”. What this means is: “let’s loop over our days array, and on each iteration of the loop, the item being iterated over will be referred to as: day.

On each iteration of the loop, Angular will create a list item with a paragraph inside of it. Inside the paragraph, we have a placeholder for the day variable in our loop. So {{day}} will be replaced with “Monday“, “Tuesday“, “Wednesday“, etc.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kc-angular-ngFor

Summary

I think most would agree that the Angular ngFor directive provides a powerful way to iterate over your data and render DOM elements. You’ll find that as is often the case with Angular, this directive saves you time and effort as it takes care of the most tedious aspects of this kind of challenge. Just add this to your bag of resources and you can rely on Angular to minimize human error and provide a more reliable solution for data iteration and DOM rendering.

How do I use the Angular ngClass attribute?

Angular

Angular logo - ngClass

The Angular ngClass attribute allows you to programmatically determine if a CSS class will be applied to an HTML element.

We know that adding and removing CSS classes is a common JavaScript task. Quite often, it is the most efficient way to make style changes to one or more DOM elements. In fact, there is a great deal of power in this approach, with its ability to add or remove one CSS class that can cascade, causing dozens, hundreds or even thousands of child elements to change in appearance. But when leveraging Angular, there is no need to manually add or remove CSS classes to or from DOM elements; Angular just takes care of this, based on the state of your data. So, as you’ll see in the examples below, the most efficient way to go is to use the Angular ngClass attribute, which allows you to determine if a CSS class should be added to a DOM element, based on the result of a JavaScript expression.

Sometimes you may want to apply some CSS to an element, based on the value of some data. And sometimes you may want to apply other CSS when that data changes, or if it has a very specific value. With the ngClass attribute, Angular makes this kind of CSS logic arbitrary.

Example # 1

In Example # 1, we have our component. This code example is short, as there is only one thing to point out: the contentHighlighted property. This property is a boolean, so it will always be either true or false. We will pay attention to this value in our template.

Example # 2

In Example # 2, we have our Angular template. First, let’s take a look at the buttons. The first button sets the contentHighlighted property to true. It also has an ngIf attribute set so that when contentHighlighted is true, the button is destroyed. The second button functions in the exact opposite way: it sets the contentHighlighted property to false, and is destroyed if contentHighlighted is false. When you run the example code, you’ll notice that button’s toggle. That is to say: when you click one, it disappears (i.e. is destroyed) and then the other button appears (is created), and vice verse.

Next, look at the style element. There, we’ve defined a highlighted class. So, any element that has the highlighted class gets an outline and pastel yellow background.

Finally, we have the div with the ngClass attribute. Based on the syntax, we have declared that if the contentHighlighted property is true, then the highlighted class will be applied to this element. Conversely, if the contentHighlighted property is false, then the highlighted class will not be applied to this element. When you run the example code, you’ll see that as you toggle the buttons, the highlighted class is toggled on that element, and when it is applied, then that element gets the outline and pastel yellow background.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-ngClass

Sumary

The Angular Ngclass attribute allows you to programmatically apply one or more CSS classes to a DOM element. The CSS class is applied or removed, based on the result of a JavaScript expression, and any valid JavaScript expression can be used. This is much more efficient than manually applying or removing CSS classes. It just provides so much power when you’re trying to make small or large style changes to your component and its children.

How do I disable an HTML element with Angular ?

Angular

Angular logo - disable an html element

Set the disabled attribute to the result of an expression and Angular will disable / enable the element for you as needed.

Disable an HTML Element – Example # 1

In example # 1, we have our component. There are two properties we are interested in: count and buttonDisabled. We will leverage these in our template.

Disable an HTML Element – Example # 2

In example # 2, we have our template. There are three buttons. The first two buttons toggle each other. That is to say, when the first button is clicked it is destroyed, and the second button is created. Conversely, when the second button is clicked, it is destroyed and the first button is created. All of this happens because each button has an ngIf attribute. That attribute is watching for the value of the buttonDisabled property. Also, each button has a click attribute. In each case, clicking the button updates the value of the buttonDisabled property.

Important note: these two buttons are for demonstration purposes only. The focus of this article is the Angular [disabled] attribute.

Next, take a look at the third button. It has a disabled attribute. That attribute is set to toggle based on the buttonDisabled property. So when the buttonDisabled property is true, that third button is disabled. And when the buttonDisabled property is false, the third button is not disabled.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-disabled-attribute

How do I get the value of the selected dropdown menu item with Angular?

Angular

Angular logo -routing

Learn how to determine which dropdown menu the user selected in your Angular template, and get its value.

Dropdown elements provide a way to give your visitors choices. Technically, a dropdown element is actually a select element and each menu item in the dropdown is an option element. In a pure HTML-based form, there is virtually no work to do; the browser takes care of all the heavy-lifting. But with Angular, you need to do a little bit of the work. The key is to examine the event object. It contains information about the user’s action.

The reason that we care about the event object is that the select element contains one or more children, and we are going to attach a handler to the (change) event of the select element. But, hold on… even though a change event fired on the select element, we’re concerned with more than just the fact that there was a change; we want to know which one of the option elements was selected. So to do this, we need to take a look at the event object that is passed to the handler assigned to the change event of the select element. And when we look at that event object, we want to pay particular attention to the event target, and get its value. For instance: “event.target.value”, in Example #1.

Example # 1

In Example # 3 we have the contents or our component. There is a selectedDay property, which will be used to display the value of the selected dropdown menu item. There is also a selectChangeHandler method. This method takes an event object as its sole argument. When executed, this.selectedDay is set to the value of the event.target.value property.

So here, you’ll see our event handler because it’s generally considered best practice to define methods in your component, and then assign those methods to the event attributes of the HTML elements in your template. In Example # 2, however, you’ll see that we assign the selectChangeHandler method to the (click) attribute of our select element in the template.

Example # 2

In Example # 2, we have our Angular template. There is a select element, which has five option elements inside of it. Each of these option elements translates to a dropdown menu choice.

The select element has a change attribute. We assign that change attribute to the radioChangeHandler method, passing it the $event object. In ourselectChangeHandler method (see Example # 1), we take a look at the event object. That is, we want to know about its event.target.value property. We set the value of that property to the selectedDay property of our component (in the radioChangeHandler method, we refer to it as this.selectedDay). By setting the selectedDay property of our component, the UI is updated with whatever value is assigned to that property.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-option-get-value

Summary

So now we have the full picture: getting the value of the selected dropdown menu item with Angular requires that an event handler be set for the (change) attribute of a select element. But because select elements have one or more children (i.e. the option elements), we need to inspect the event object that is passed to the change event handler. And by referencing the value property of the event target, we can determine the selection that was made by the user. So this workflow requires a bit more effort than is usually the case with Angular, and part of the reason for that is: we are not using any other JavaScript library such as jQuery, so we need to use vanilla JavaScript in order to determine which drop down menu choice was selected. A little more work here, but to get to what you’re after, it’s worth it.

Angular Routing Basics

Angular

Angular logo -routing

Basic Angular routing is easy to set up. You’ll need to define your routes and the components that should handle each one, in routes.ts .

With any single page application, routing is important. The main reason for this is: users will spend most of their time on the same page. Angular provides routing for your application so that you can divide it into logical parts. These parts make sense not only from a UI perspective, but also programmatically. That is, you want each logical part of your application to live in a relatively small, organized collection of files.

So, let’s begin with what every Angular application needs, which is a routes.ts file. And even if you have only one route, it is best to set up your routing with routes.ts. The main reason for this is: you may want to expand your routing in the future, so why not include this in your application’s architecture now. It’s great planning. Also, you may want to define a component that should handle any routing errors (that is, which component should be instantiated if the user tries to navigate to a non-existing route). As you’ll see in the following examples, any components that will handle routes should be defined in app.module.ts, and then you can use them in your routes.ts file. So let’s take a look at those examples:

Example # 1

In Example # 1, we have our app.module.ts file. The important thing to note here is that you need to declare your components in this file. Our application has three routes: home, products and about. So we need to declare those components here in app.module.ts.

Example # 2

In Example # 2, we have routes.ts. This is where we set up our routes. There is a Routes constant, and it is an array. Each element in this array is an object. Each object has a path property and a component property. The path property defines the string that represents the route that appears in the address bar. For example: “/#/home”. The component property determines which component will handle this route. In each case, the component that matches the specified path property is defined.

You may have noticed that although we have three routes, there are four elements in this array. This is because we have defined a default route. The first element in the array has a path property of: “” (an empty string). It does not have a component property. However, it does have a redirectTo property. What this means is: when a route is not specified, redirect to the home route. So, when the user navigates to the root of the application (i.e. “/”), they are taken to the home route. This value can be any one of our existing routes, so we could have also configured products as the default route.

Example # 3

In Example # 3, we have the HTML for our navigation component. For each navigation item, there is a [routerLink] attribute. This connects the appropriate route to the click event of that HTML element. In each case, the appropriate route has been defined.

So now, whenever a navigation item is clicked, its [routerLink] attribute connects that action to the appropriate component. This will happen because we set a one-to-one mapping between routes and components in the routes.ts file. So, for example, we can have something like: [routerLink]=”[ ‘/home’]”.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-routing-basics

Summary

Routing allows you to organize your code into logical units that mirror the navigation choices available to the user, and that’s a good thing. In fact, defining your routing in a routes.ts file is considered a best practice. The routes.ts file provides a one-to-one mapping between routes and the components that should handle each route respectively. And your routes.ts file also allows you to define which component should handle cases in which a non-existent route is attempted. But don’t forget that essential detail: each component that you leverage in routes.ts must first be defined in your app.module.ts file. Routing in Angular is not difficult, but it does require some effort when you start putting together your application. These basics are an important part of any single page application.

Angular HTTP get basics

Angular

Angular logo - httpMaking an HTTP get request with Angular is fairly simple. What may seem a bit different is the way that you handle the request. Instead of nested callbacks, you set up a subscription that can handle a stream of data.

It’s difficult to imagine an Angular application that does not make HTTP GET requests, because making network requests is at the very heart of any Angular application. It’s one of the basics. And for any front-end web developer, an HTTP GET request should be nothing new; it’s a simple one-way transaction. You simply request a remote resource such as a HTML file, CSS file or JavaScript file, and that resource is returned to you. Most front-end web developers will leverage a JavaScript library such as jQuery to make HTTP GET requests, rather than piecing together vanilla JavaScript which has to instantiate the XMLHttpRequest object. But while there is nothing wrong with this approach, it can result in boilerplate code and much of that code will become difficult to manage as it scales. So, most would agree that this should really be avoided.

Angular’s HTTP module provides a get method, and on a very high level, it provides similar functionality to the jQuery.get() method. The biggest difference between the jQuery.get() method and the Angular HTTP.get method, is in what each returns. While the jQuery.get() method returns a promise, the Angular HTTP.get method returns an observable. Important to note that this observable is markedly more sophisticated than a JavaScript promise. You subscribe to this observable, rather than passing a callback to it (as is the case with a promise). Significantly, as a subscriber of this observable, you are notified any time the data stream changes. For a closer look, take check out the examples that follow.

Example # 1

In Example # 1, we have our home component. We have imported RXJS components because we will need those in order to handle the HTTP get request. In this case, the real action happens in the ngOnInit method. This method is executed when the component is initialized, so we know that our code will be executed each time the user navigates to this route. Inside the ngOnInit method, we get ahold of the http service (i.e. this.http), and execute the get method, passing it the URL of the HTTP request we need to make. We then chain the map method to the result of this get request, returning JSON.

Next, we chain the subscribe method. Here we are setting up a subscription to this data. What this means is: whenever there is new data, we want to “know about it”. We pass an anonymous function to the subscribe method, and inside of that function, we can handle the new data. In this case, what we do is set this.destinations to the new data.  The reference: this.destinations  is the destinations property of our component. We use the “this” keyword because we are inside of a method, and the “this” keyword gives us access to the component. Setting this.destinations  to the streamed data will update the UI, which we will look at next.

Example # 2

In Example # 2, we have our Angular template. This is an unordered list. There are numerous destinations in our streamed JSON data, but we only create one list item. The reason for this is: we use the ngFor attribute to create a list item for every destination in the destinations array. In each iteration of this array, we reference the destination variable, and display the various properties of that object such as countryCode, nameduration and price. These values appear in the UI.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-http-get

Summary

Unlike the jQuery.get() method, Angular’s HTTP.get() method returns an observable (rather than a promise), and observables are more sophisticated than promises. We also know that when you subscribe to an observable, you are notified each time the data stream is updated. Another strength of the observable design pattern is that it allows for more than one party to subscribe to it, and these subscriptions can be cancelled at any time. Now while the syntax needed to set up an HTTP GET request in Angular is fairly simple, consuming observables might take a little getting used to. But it’s every bit worth the effort: observables are powerful.

How do I set up an Angular click-event handler?

Angular

Angular logo - click

Setting up a click event handler in Angular requires the click attribute and an expression or method assignment.

It’s hard to imagine any modern web page that does not have at least one click-event handler. And while anchor tags provide a scripting-free way of taking the user to a new web address, JavaScript event handlers are a common trait among web pages today. But setting up up a click-event handler that would require you to make some kind of connection between the HTML and a JavaScript method that lives somewhere in your code. In vanilla JavaScript, this means a tight-coupling between your HTML and JS code. Just keep in mind, though, that even with a library such as jQuery, managing click-event handlers can become tedious.

Angular makes event handlers simple: you add a click attribute to the element. The value you assign to this attribute depends on the approach you want to take. You can provide an expression that Angular will evaluate. For example: count = count + 1. This means that when the element is clicked you want Angular to increase the value of the count property by one. You can also assign a method. This means that you want Angular to execute a method when the element is clicked. You can also pass parameters to this method.

Let’s look at a couple of examples, to see how this works:

Example # 1

In Example # 1, we have our component. Note the content property, which is a string and the count property, which is a number. We will display these properties in the UI. There is also a setMessage1 method. This method assigns a value to the content property. We refer to the content property as this.content inside of that method because the this keyword provides access to the object to which this method belongs.

Example # 2

In Example # 2, we have our template. There are three buttons. Each has a click event handler set up via the click attribute. The first button has a method assigned to the click attribute. We reviewed the setMessage1 method in the first example. This method sets the content property to  “This is message # 1”. This allows us to see in the UI that the first button was clicked. This approach is mostly likely one you’ll take when setting up a click event handler with Angular. The advantage here is that inside of the setMessage1 method, you can execute more than one task (i.e. you could do more than simply set the value of the the content property).

The second button takes a different approach: it sets the value of the content property directly. This is because an expression is provided as a value to the click attribute: “This is message # 2”. This approach is perfectly fine, but somewhat limited; you can only accomplish one thing.

The third button takes the same approach, but instead of setting the content property, it increases the count property. Also, the button’s text is updated by the {{count}} binding.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-click-attribute

Summary

The key to setting a click event handler in an Angular template is the (click) attribute, and you now know that you can take one of two approaches: 1) you can assign a valid JavaScript expression to the (click) attribute, for example: “count = count + 1” or, 2) you can assign a method to the (click) attribute, as long as that method is a property of the component to which the template belongs.
Just keep in mind that the first approach is limited in that you can only accomplish one task when the element is clicked. The second approach, on the other hand, is more powerful; in the method that you assign to the (click) attribute, you can execute arbitrary code, which means that a limitless number of tasks can be accomplished. So the thing for you to do, at the outset, is to decide which approach is best for what you’re planning to do.

How do I use the Angular ngIf Directive?

Angular

Angular logo - ngFor

Angular’s ngIf directive does not simply hide and show. It creates and destroys an HTML element based on the result of a JavaScript expression.

It’s perfectly fine to use the Angular ngIf directive to hide / show one or more HTML elements. This is the net effect and when used wisely, there is no problem with this usage. But it is important to be aware that Angular’s ngIf directive actually creates a DOM element or destroys it. If you want to actually hide / show elements without destroying them, then the Angular ngClass attribute would be more appropriate.

The thing to keep in mind when considering whether or not to use the Angular ngIf directive is performance. For example, if you have have hundreds of DOM elements, but do not need to show ALL of them when the component initially renders, then the Angular ngIf directive might be better for performance reasons. As you’ll see, the benefit of this is that only tens or a few hundred DOM elements are created at a time. So this means that as your data changes, the creating / destroying of elements is restricted to fewer elements. But if you have a total of tens or perhaps less than 100 DOM elements to manage in your component, then the Anglular ngClass attribute might be a better choice. You’ll find that performance is improved when using the Anglular ngClass attribute because DOM elements will be hidden-shown via CSS, not JavaScript

Example # 1

In Example # 1, we have our component. There is a contentVisible property. It is a boolean, and set to false by default. We will consume the contentVisible property in our template (see Example # 2).

Example # 2

In Example # 2, we have our template. Notice that the div element has an ngIf attribute. This attribute’s value is the result of the contentVisible property. So if the contentVisible property is true, then the div element is created. Conversely, if the contentVisible property is false, then the div element is destroyed. The net effect is that the element is hidden / shown, but it is important to note that the element is actually created / destroyed.

There are two buttons in the template. Each button has a click event handler. In each case, the button sets the value of the contentVisible property. Each button also has an ngIf attribute. Because they both change the value of the contentVisible property, they change the visibility of both buttons. That is to say, when the first button is clicked, it is immediately destroyed and the other button is created, and vice verse.

The main thing to note in this example is that these buttons change the value of the contentVisible property, which seems to hide / show the div. However, the div is actually being created and destroyed.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-ngIf

Summary

So, it’s important to understand that the Angular ngIf directive actually creates and destroys DOM elements. The Angular ngIf directive could be a strong or weak design choice, depending on the context of your component. It’s also a DOM management choice, and whether or not you’re working with hundreds or thousands of DOM elements. So, overall, the approach you take could have a major impact on the performance of your component.

ERROR in [at-loader] Duplicate function implementation

Jasmine

Angular Logo

If your wrap your unit tests in one global function, that function name must be unique across all of your tests

I have some OCD issues. I guess that’s why I like writing code. My OCD tendencies are no less apparent in my unit tests: I tend to wrap all of my tests in a global function.

The main reason for this is: test data.

Test data is a reality of unit tests and something that happens often. But I really hate to see a whole bunch of boilerplate code at the top of a unit test. I don’t want to see all of that, I just want to jump into the tests. So what I do is: I create all of the test data at the bottom of the file. I feel that this makes the unit tests much easier to read.

But since I want all of the test data to be available before the tests run, I wrap all of the tests in a function, create the test data, and then execute the function that contains all of the tests.

Example # 1

In example # 1, I’ve set up a unit test. The test data is at the top of the file, which to me make the test hard to read.

Example # 2:

In example # 2, I wrapped the unit tests in the function: runTests. This way I create the tests, create the test data, and then execute the runTests function. I like this approach because my test data is at the bottom of the file, and the actual unit test is at the top, which I feel makes the code easier to read.

After upgrading to Angular 4 (and subsequently upgrading the npm packages karma & karma-jasmine), I got a whole bunch of instances of this error: ERROR in [at-loader] Duplicate function implementation. I don’t get the error if there is only one unit test, but as soon as I introduce more than one unit-test file, I get the error (and the more files there are, the more errors there are).

This took a bit to figure out, but I finally got it. My runTests function is a global, and Jasmine does not like when there is more than one instance of it declared.

Example # 3:

In example # 3, I renamed the runTests function to runTests_ServiceA. And in each unit test file, I did the same exact thing. For example: runTests_ServiceB, runTests_ServiceC, runTests_ServiceD, etc…

This way, each runTests function  has a unique name. While I don’t always have test data, this is just a pattern I like to follow. The latest versions of the karma & karma-jasmine npm packages did not like the fact that multiple instance of the runTests function  were being declared, so I just make sure that in each unit test file, that function has a unique name. An easy way to do this is to simply append “_ServiceName” to runTests. But as long as the function name is unique, any name will do.

Jasmine – parameter XXX implicitly has an “any” type.

Jasmine

Angular Logo

After upgrading from Angular 2 to Angular 4, Jasmine started to complain about values that did not even exist in my unit tests

I recently posted an article about a Jasmine issue that arose with regards to the globals: describe, beforeEach, expect and it. That turned out to be related to how types are handled in Angular 4.

Once I got that problem straightened out, there were some really odd errors. The thing that was driving me nuts was: the values that Jasmine complained about did not even exist in my unit tests… gggrrrrr.

This is one that could have taken forever. Actually, I did spend at least 30 minutes scratching my head. Fortunately, I found the answer on Github: I needed to make a change to tsconfig.json. In the compilerOptions object, set noImplicitAny to false.

For example:

Credit goes to Zama Khan Mohammed for this answer.

 

Jasmine – Cannot find name describe (or beforeEach, expect and it)

Jasmine

Angular Logo

After upgrading from Angular 2 to Angular 4, there were some delightful new errors in my unit tests

After some initial hair-pulling, I’ve finally got my unit tests working again after upgrading from Angular 2 to Angular 4. But once I started running the tests, I found these lovely errors:

I knew it could not be the unit tests themselves; it had to be something low-level. Then it occurred to me that in my Angular 2 implementation, I had a typings.json file in the root of my application to handle types such as jasmine , lodash and moment. But with Angular 4, types are handled in package.json via the @types namespace.

So, after some searching, I found this Stackoverflow article: Angular 2 Unit Tests: Cannot find name ‘describe’. The solution provided worked perfectly for me.

Two Steps:

1 – In package.json, add this line to your devDependencies:

2 – And then in your unit test file (i.e. XXX.spec.ts), add this line:

All of the errors that complain about describe, beforeEach, expect and it should no longer appear in your terminal.

Major credit goes to ksharifbd for this answer. This was a major time-saver!

Angular2 HTTP Observables in Five Minutes

Angular 2

rxis angular2 observablesObservables are the way to stream data in Angular2. Here’s how to get it working.

Managing asynchronous activities in any JavaScript-driven application can be tricky. Every framework / library has an approach, and there are proven design patterns that are worth considering. In Angular 1.x, $q is the engine that drives this. In Angular 2, it’s RxJS. This technology is not for the faint at heart. It’s very cool, and works well, but does take some getting used to.

This article has one focus: providing example code that demonstrates how to create an observable, and then consume it. So you can start out by cloning the Github repository below. Once you’ve done that, you can run the example code locally and see it in action.

https://github.com/kevinchisholm/angular2-http-observables-in-five-minutes

 

Making the HTTP request

In the following example, we will make an HTTP request, and then stream the return data to anyone who has subscribed to it.

Example # 1

In Example # 1, we have the code for the PackageService service. This service makes the HTTP request for the JSON data. I’m using myjson.com so that we don’t have to spend time with implementation details about serving up the JSON. We just want to make the request and then talk about how we can share that data across our application via an RXJS stream.

So let’s talk about this line:

Here we create the packageData property.  Although it will be an array, it will be a BehaviorSubject instance. So when we define the property, we specify that it is of type: Subject. Then we instantiate the BehaviorSubject class, passing it an empty array. The reason for the empty array is that we don’t want to stream “undefined. Somewhere else in our code, there is a consumer who will want to subscribe to this stream. That consumer expects an array. It’s fine if the array is empty at first. We just don’t want the consumer to get “undefined“.

Later in Example # 1, we call the http.get method. We map that result to JSON, and then we subscribe to that JSON. I don’t want to get into too many implementation details about the last sentence, as I promised that this would take “five minutes.” So let’s focus on the next line: subscribe. By subscribing to this JSON, we are saying “Hey, any time there is  a change in this JSON, I want to know about it.” And when that change occurs, then the function you see passed to the subscribe method is executed.

That function will receive the updated JSON data as its first argument. The very next line is critical: this.packageData.next(data). What’s happening here is: the packageData object that we created earlier has a “next” method. That method takes an argument, which can be anything. In our case, it is the JSON data. So, anyone who has subscribed to our packageData property will receive a notification that there is new data and will be passed that data.

Example # 2

In Example # 2, we have our PackagesComponent component. So let’s zero-in on the critical part: the ngOnInit method. Well, as you probably guessed by the name, this method is executed when our component is initialized. Take a look at this line: this.packageService .packageData .subscribe. There we are subscribing to the packageData property that we created in the packageService service. Because that is an instance of BehaviorSubject, subscribing to it gives us a live connection to anything it streams out. In our case, the http.get request fetched some JSON data. And in that service, the JSON data is streamed out via the  line: this.packageData.next(data). The JSON data comes to the subscribe callback via the variable: “packages.” So we set this.destinations = packages. Therefore, at that point, the UI is updated and we see the list of travel packages in the page.

Summary

I promised that this would take less than five minutes. Hopefully, it did. RXJS is a deep subject that takes some time to get familiar with. I wrote this article because the first time I needed to stream the result of an HTTP request in an Angular2 application, it was a giant pain in the rump.  But here, I have tried to provide an easy example of how to sketch out this scenario and get it working quickly. I hope it was helpful!