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.

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

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

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.

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.

How do I get the value of the selected radio button with Angular?

Angular

Angular logo -routing

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

Radio buttons provide a way to give your visitors mutually exclusive choices. 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.

Now the reason that we care about the event object is that the select element contains one or more children. So we’re going to attach a handler to the (change) event of the select element. But, 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 which is assigned to the change event of the select element. And when we do look at that event object, we want to examine the event target, and get its value. Take, for instance: “event.target.value”, in Example #1.

Example # 1

In Example # 1, we have the contents of our component. There is a selectedDay property, which will be used to display the value of the selected radio button. There is also a days property. The days property is an array, which contains the five days of the work week. This array will be used in our template so that we don’t have have to actually create five radio buttons. We will use the ngFor directive to loop over the elements of this array. For each element in the array (i.e. for each “day of days”), we create a radio button.

We’ve leveraged the ngFor directive to create the radio buttons programmatically. And in Example # 2, you’ll see that we assign the radioChangeHandler method to the (click) attribute of each of the radio button elements in the template.

Example # 2

In Example # 2, we have our Angular template. Instead of manually writing out five radio buttons, we leverage theAngular ngFor directive. In this directive, we loop over the days array that was defined in our component (see Example # 1). In our ngFor directive, we provide the value: “let day of days“. This means that for each iteration of the loop, the element being referenced will be known as day. Each, time, we use that reference to create the radio button.

Each radio button has a change attribute. We assign that change attribute to the radioChangeHandler method, passing it the $event object. In our radioChangeHandler 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). But setting the selectedDay property of our component, the UI is updated with whatever value as assign 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-radio-get-value

Summary

So here, we’ve found that getting the value of the selected Radio Button with Angular requires that an event handler be set for the (change) attribute of each element. We then see that we have to inspect the event object that is passed to the change event handler. Then, by referencing the value property of the event target, we can determine which radio button was clicked by the user. Now even though this workflow requires the use of vanilla JavaScript, which is a bit more effort than is usually the case with Angular, it’s worth it so we can make that determination about which Radio Button was clicked.

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.

Angular 2 rc4 Upgrade Links

Angular

Angular Logo

Upgrading from Angular beta to Angular RC is a little painful, and things are going to break. I’ve put together some links that helped reduce some of that pain for me.

A few weeks ago, I had the pleasure of upgrading a client’s singe page application from Angular 2.0.0-beta.12 to Angular 2.0.0-rc.4. As soon as I updated package.json, it broke. I was not surprised, I figured this would happen. Unfortunately, there were more than a few things to fix. Fortunately, the fixes fell into three categories:. 1) The Angular namespace changed. 2) The router changed. 3) Unit tests had to be changed.

None of this was fun, but I got through it. The hardest part was the lack of documentation. I found plenty of out-dated articles with tons of information that was useless to me. Awesome. But the official documentation was minimal to none. And what I found was either tedious  or virtually useless. C’mon ng-folks, you can do better than that.

Here are some links that did provide helpful content for this upgrade:


angular/CHANGELOG.md at master · angular/angular

https://github.com/angular/angular/blob/master/CHANGELOG.md

Details: Essential information for each version release. I can’t imagine living without this. In particular, you can find out about namespace changes.


Forms Upcoming Change Proposal

https://docs.google.com/document/u/1/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub

Details: Explains the thought-process behind their change to forms. At the very bottom of the article is critical information about how to opt-in to the deprecated forms, or use the new forms module.


Issues after Migration to RC4 in angular2 – Stack Overflow

http://stackoverflow.com/questions/38154399/issues-after-migration-to-rc4-in-angular2

Details: Some helpful information on breaking changes.


Routing & Navigation – ts

https://angular.io/docs/ts/latest/guide/router.html

Details: A very detailed explanation of how the new router works. A long read, but also one of the few thorough their documentation pages.


Defining Child Routes · Rangle.io : Angular 2 Training

http://angular-2-training-book.rangle.io/handout/routing/child_routes.html

Details: Another very detailed explanation of how the new router works.


Plunker

https://plnkr.co/edit/6Mdn7qUblMtktpQyFJAc?p=preview

Details: This plunker is very helpful if you need a quick-and-dirty working example of how child routes work in the new router.

Angular2 Http double subscribe

Angular

stack overflow logoI working on a new Angular 2 service today that wraps the HTTP class. The purpose of this service is to intercept errors, and log the user out when the HTTP status code of the error object is 401.
Everything seemed fine until I realized that each GET and POST was firing twice. After a lovely hair-pulling session, I realized that it was the 2nd observable subscription that was causing the double network calls. Messy stuff.

If you find yourself wresting with the same problem, this Stack Overflow answer nails it. Cheers to dfsq for his great answer:

http://stackoverflow.com/questions/35397710/angular2-http-double-subscribe

What are the Five Ways to Create an Angular Service?

Angular Services

Angular.js LogoThere is a lot of confusion over the difference between the angular’s factory, service and provider methods. This article explains the different ways that an Angular service can be created.

The official Angular 1.4.0 documentation page describes services as: “…substitutable objects that are wired together using dependency injection (DI)” Stating: “You can use services to organize and share code across your app.” While a bit dry, I think this is actually a perfect description. I think that many who are new to Angular are confused about which of the many methods available should be used when creating a service. Fortunately, the answers are fairly simple and straightforward.

Five Ways to Create an Angular Service

The angular.value method

The value method, one the most overlooked approaches, is most commonly used to turn a global into an injectable Angular service. While the approach is simple, the application is powerful: the value of your service is testable and can be shared across your application.

Example # 1A

 Example # 1B

Examples 1A and 1B use the exact same syntax when creating an Angular service. The only difference is their value. Example # 1A’s “speed” service is a primitive: the number 100. Example # 1B’s value is an object with a “title” property.

The angular.constant method

This works the same as the angular.value method. The difference is that it is available during the configuration phase of your Angular application. Also, the value of a this constant can never be changed.

Example # 2

 The angular.factory method

The angular.factory method takes two arguments: a string and a function. The string represents the name of the service, which will be used to gain access to this service (e.g. to inject this service into a controller as a dependency). The anonymous function that you provide as the second argument provides the actual implementation. When you register your service, Angular will execute this function.

The only difference between angular.factory and angular.service is that the callback function you provide with the service is instantiated. With the factory method, it is executed.

Its return value is cached and will be shared with any component of your application that injects the service. It is important to note that this function will only be executed once.

This is the scenario most are thinking of when they intend to create an Angular service, and probably the most common approach.

Example # 3

In Example # 3, we create a service named “myService”. Any component that lists this service as a dependency will receive the object that you see returned. This object has one method: “sayHello”.

The angular.service Method

This approach is similar to the angular.factory method with one big exception: the function that you provide is treated as a constructor and is instantiated. It is important to note that this function is instantiated only once and every component that injects your service as a dependency shares the same exact cached object that this instantiation returns.

Example # 4

Example # 4 is very similar to Example # 3, except that the latter uses the JavaScript “this” keyword when defining the properties and methods of the object that the service returns. The reason is: the function provided when registering the service is instantiated (i.e. treated as a constructor), not just executed.

The angular.provider method

This approach is the most complex of the five. The angular.provider method is actually used under the hood by all four of the other service registration approache. While this approach is more verbose, it provides a powerful feature that the others do not: the service you are registering is available to your application during its configuration phase. This is useful when creating a service that will be shared across multiple applications and needs to be configured in order to work properly.

When using angular.provider, there are two important details to keep in mind:
  1. The callback function that you pass to the angular.provider method will be treated as a constructor – This means that the callback will be instantiated for each application that it is registered with, and its return value will be shared by all components that inject that service.
  2. The callback function that you pass to the angular.provider method must have a $get method – When you inject a service into a component that was created using the provider method, Angular will call that services’ $get method to retrieve the object to inject.

Example # 5

In Example # 5, we have created an angular service named “helloWorld”. This service is available during the configuration phase of your application. After registering the service, we call the app.config method, passing the “helloWorld” service as an argument to the anonymous callback function. Inside of that callback, we use the services “setName” method to set the value of its “name” property. We could use the “helloWorld” service in a different application and set that “name” value to something different, as needed.

Summary

Most of the time, the angular.factory method is the approach that is desired / used. This does not mean it is the “right” way to create an Angular service. The approach you take should be driven by the problem you are looking to solve. angular.value and angular.constant are often helpful when you need to share a simple value across your application (keeping in mind that the value returned by angular.constant cannot be changed). The angular.service method is helpful when you want your service to be instantiated, and the angular.provider method provides a way to configure your service before any component gains access to it.

Helpful Links for Understanding the Different Ways to Create an Angular Service

https://docs.angularjs.org/guide/services

http://blog.pluralsight.com/angularjs-step-by-step-services

https://blog.codecentric.de/en/2015/03/five-ways-to-write-better-angular-services/

Getting Started with Angular 1.x Custom Directives – Part III – The “restrict” property

Angular

Angular.js LogoLearn how the “restrict” property determines how your Angular.js directive can be invoked

In the second part of this series: Getting Started with Angular.js Custom Directives – Part II – The “replace” property, we learned about how to use the “replace” property when creating a custom Angular.js directive. This determines whether the element that your directive renders will be a child of the element that invoked it, or a complete replacement of that element.

In this article, we will learn about the “restrict” property that, which allows you to specify the ways in which your custom directive can be invoked.

Example # 1:

 

In Example # 1, we have created a custom Angular.js directive named: “uiWidget”. In addition to the “template” and “replace” properties that were discussed in previous articles, we have created a “restrict” property. This property allows you to specify the way in which the directive is invoked. Notice that the value is: “AECM”. These letters stand for:

  • A : Attribute
  • E : Element
  • C : Class
  • M : Comment

You can use any one of the values by itself, or any combination.

Example # 2:

In Example # 2, we have four snippets of HTML. In each case, we demonstrate a different way to invoke our custom Angular.js directive.

First, as an attribute of the HTML element. Notice how the attribute has no value. In our case, the mere presence of the attribute signals to Angular that our custom directive should be invoked.

Second, as an element. Although there is no such thing as a “ui-widget” HTML tag, Angular will recognize this element and invoke our custom directive.

Third, as a CSS class of the element.

Fourth, as a comment. This approach may seem a bit odd, but you can, in fact, trigger your custom Angular.js directive via an HTML comment.

HERE IS THE LINK TO THE WORKING EXAMPLE FOR THIS ARTICLE: http://examples.kevinchisholm.com/angular/directives/basics/html/part-iii.html

Summary

In this article, we learned about the “restrict” property of the object returned by an Angular directive. We discussed the four possible values for this property, and how each case differs.

Getting Started with Angular. 1.x Custom Directives – Part II – The “replace” property

Angular

Angular.js LogoLearn how your Angular.js directive’s “replace” property determines how it is rendered in the DOM

In the first part of this series: “Getting Started with Angular.js Custom Directives – Part I“, we learned the absolute basics of how to create a custom Angular.js directive. In that article, we learned how to create an Angular module, and then call that module’s “directive” method, which takes a function as its second argument. In that function we returned an object with a “template” property, which contained HTML that would become the actual directive, once injected into the DOM.

In this article, we will learn about the “replace” property, which is a member of the object returned by the directive method. This property is a Boolean, so it has two possible values: true and false. When false, your directive’s HTML is injected into the DOM as a sibling of whatever content is already there. When true, your directive completely replaces the element.

Example # 1A:

In Example # 1A, we have HTML that invokes two Angular directives: “ui-widget-replace” and “ui-widget-no-replace”. Both DIVs look are empty and other than the slight variation in the directive name, they look identical.

Example # 1B:

In Example # 1B, we have the JavaScript that defines these two directives. The “uiWidgetNoReplace” directive has its “replace” property set to: “false”. As a result, the widget that is rendered in the DOM is a child element of the element that invoked the widget (i.e. the element with the “ui-widget-no-replace” attribute). The “uiWidgetReplace” directive has its “replace” property set to: “true”. As a result, the widget that is rendered in the DOM REPLACES the element that invoked the widget. In other words: the element with the “ui-widget-no-replace” attribute is replaced by the widget.

Example # 1C:

In Example # 1C, we see the result of our HTML and JavaScript. The first element completely wraps the widget markup, whereas the second element is the widget (i.e. the widget has completely replaced the markup that declared the ui-widget directive).

This result can be verified when you look at the link for the working example. The element with the attribute: “ui-widget-no-replace” has a blue border, and the element with the attribute: “ui-widget-replace” has a red border. Also, you’ll notice that the first widget is has an inner box with a yellow border. This is because there is a parent-child relationship going on here; because the “replace” property’s value is false, the widget is injected into the DOM as a child of the element that invoked the directive. You can view the page source and examine the CSS to see how this style has been applied.

IMPORTANT: Note that we actually create three modules: “myModNoReplace“, “myModReplace“, and “myMod“. The “myMod” module is the main component used in the page, and it declares the modules: “myModNoReplace” and “myModReplace” as dependencies. Module dependencies is a topic that is beyond the scope of this article, and will be covered in a future post. Just know that in order to have multiple modules used in a page, you’ll need to follow this kind of pattern.

HERE IS THE LINK FOR THIS ARTICLE’S WORKING EXAMPLE:

 http://examples.kevinchisholm.com/angular/directives/basics/html/part-ii.html

Summary

In this article, we learned about the “replace” property. This boolean value allows you to determine whether or not the HTML that makes up your custom directive will completely replace the element that declares our directive, or make it a child element.

Getting Started with Angular 1.x Custom Directives – Part I – Introduction

Angular

Angular.js Logo
Learn how to create your own Angular.js directive (it’s much easier than you think!)

It’s hard to imagine any kind of interaction with Angular that does not involve directives. Angular directives allow you to super-charge your HTML, or even create your own tags.

While there is certainly a generous helping of built-in Angular directives, you don’t have to be satisfied with what comes in the box. You can create your own Angular directives. Not only that, but the way your directive is invoked, what it does, and how it works is completely up to you. Because of the kind of abstraction Angular provides, you are limited only by your imagination.

In this article, we will learn how to create our own Angular directive. This is a fairly deep topic, with plenty of detailed discussions to jump into, many of which will be covered in upcoming editions of this series. For this article, we will focus on the core syntax needed to create a directive and have it render something in the DOM.

Example # 1A

In Example # 1A, we create an angular module named: “widgetApp”, and assign it to the variable “myMod”. The syntax is pretty simple: You call the module method of the angular object, passing it two arguments. The first argument is a string, which is the name by which this module will be known by other modules. What is this means is that if this module is to be considered a dependency by one or more other modules, this string is the name by which those modules will call your new module. The second argument is an array. This array can contain one or more dependencies. If your directive will have no dependencies, you can leave this array empty, but it must be there (i.e., you can’t omit the array).

Example # 1B

In Example # 1B, we have created a custom directive by calling the angular.module’s “directive” method. The first argument is a string: the directive’s external name; that is, this is the name by which you will refer to your directive in the DOM.

The second argument is a function. This function is where we will do the work required to create the directive. Notice that the function returns an object. While this object is empty in our example, it is required. So, even though we return an empty object, we are ok (but you must return an object).

While this directive effectively does nothing, the syntax is correct and there will be no errors on page load. But since our directive has no actual functionality, we will need to put a bit more effort into this.

Example # 2

In Example # 2, we have made a small addition to the anonymous function that is passed to the angular.module’s “directive” method: the object that we return now has one property: “template”. This “template” property’s value is a string of HTML that will be injected into the DOM.

This could be considered the bare minimum needed for a directive that actually renders in the DOM: You return an object that has a “template” property. There is still not too much going on here. Our custom “uiWidget” directive simply adds a DIV element to whichever element calls the directive, and the text of that DIV is: “This is a Widget”.

HERE IS THE WORKING CODE EXAMPLE LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/angular/directives/basics/html/part-i.html

Hey Kevin, isn’t creating a custom Angular directive supposed to be a bit more exciting than this?

While injecting “This is a Widget” into the DOM is not a particularly eventful outcome here, the areas we covered are important. Any custom directive you create in the future will follow this exact same pattern. The are many more properties that can be members of the return object, and there is a tremendous amount of power and flexibility available when creating a directive. But remember: as you learn more about custom directives in Angular, every concept covered in this article will still apply.

Summary

In this article we learned the absolute basics about how to create a custom Angular.js directive. Although we barely scratched the surface, we did cover the critical details needed in order to create a directive that actually renders somethign in the DOM. We learned how to create an Anuglar module, and then use that module’s “directive” method to create the directive. We also discussed how the directive is created in a function, and how that function must return an object. That object’s “template” property will contain the HTML that will be rendered in the page.