JavaScript
Article
By Jeremy Wilken

A Guide to Building Quality Angular 1.5 Components

By Jeremy Wilken

This article was peer reviewed by Mark Brown and Jurgen Van de Moere. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

A scientist with various flasks and jars


2017.01.10: The article was updated to clarify the section on one-way binding, and add information on one-time bindings.

In Angular 1, components are the mechanism which allows you to create your own custom HTML elements. This has been possible with Angular directives in the past, but components build on the various improvements that have been made to Angular and enforce best practices in how they are built and designed.

In this article, we’re going to dig into the design of components and how to put them to use inside of your applications. If you haven’t already started to use components in Angular 1, you can read about their syntax and design in one of our recent tutorials. My goal is to outline some best practices that will improve the quality of your application.

It should also be noted that many of the best practices of Angular 2 are brought into Angular 1 through the new components API, allowing you to build applications that are more easily refactored later. Angular 2 has influenced the way that we think about and design Angular 1 components, but there are still a number of distinct differences. Angular 1 is still a very powerful tool for building applications, so I believe it is worthwhile to invest in improving your applications with components even if you aren’t planning or ready to migrate to Angular 2.

What Makes a Good Component?

Components should be designed with a number of key characteristics in mind to make them a powerful building block for your application. We’ll dig into each of these in more detail, but here are the primary concepts components should adhere to.

  • Isolated – The logic of the component should be encapsulated to remain internal and private. This helps create less coupling between components.
  • Focused – Components should act as a single unit for one primary task, which makes them easy to reason about and often more reusable.
  • One-Way Binding – When possible, components should leverage one-way binding to reduce the load on the digest cycle.
  • Use Lifecycle Events – The lifecycle of a component starts with instanciation and ends with removal from the page. It is to best to hook into these events to maintain the component over time.
  • Well Defined API – Components should accept configuration as attributes in a consistent manner, so it is easy to know how to use them.
  • Emit Events – In order to communicate with other components, they should emit events with appropriate names and data.

Now let’s start by looking at why and how components should be isolated and encapsulated from the rest of the application.

Components Should Be Isolated

The evolution of Angular 1 capabilities has been to enable isolated and encapsulated components, and for good reason. Some of the early applications were highly coupled with the use of $scope and nested controllers. Originally Angular didn’t provide a solution, but now it does.

Good components do not expose their internal logic. Thanks to the way they are designed, this is pretty easy to accomplish. However, resist any temptation to abuse components by using $scope unless absolutely necessary, such as emitting/broadcasting events.

Components Should Be Focused

Components should take on a single role. This is important for testability, reusability, and simplicity. It is better to make additional components rather than overload a single one. This doesn’t mean you won’t have larger or more complex components, it simply means each component should remain focused on its primary job.

I’ve classified components into four primary groups based on their role in the application to help you think about how you design your components. There is no different syntax to build these different types of components — it is just important to consider the specific role a component takes.

These types are based on my 5+ years of Angular experience. You may choose to organize slightly differently, but the underlying concept is to ensure your components have a clear role.

App Components

There can be only one app component that acts like the root of your application. You can think of it like having only one component in the body of your web application, and all other logic is loaded through it.

<body>
  <app></app>
</body>

This is recommended primarily for Angular 2 design parity, so it will be easier to migrate some day should you wish. It also helps with testing by moving all of the the root content of your application into a single component, instead of having some of it in the index.html file. The app component also gives you a place to do app instantiation so you don’t have to do it in the app run method, enhancing testability and decreasing reliance upon $rootScope.

This component should be as simple as possible. It probably will contain just a template and not contain any bindings or a controller if possible. It does not replace ng-app or the need to bootstrap your application, however.

Routing Components

In the past, we’ve linked controllers and templates in a ui-router state (or ngRoute route). Now it is possible to link a route directly to a component, so the component is still the place in which a controller and template are paired, but with the benefit of being also routable.

For example, with ui-router this is how we would link a template and controller.

$stateProvider.state('mystate', {
  url: '/',
  templateUrl: 'views/mystate.html',
  controller: MyStateController
});

Now, you can link a url directly to a component instead.

$stateProvider.state('mystate', {
  url: '/',
  component: 'mystate'
});

These components can bind data from the route params (such as an item id), and their role is to focus on setting up the route to load the other components needed. This seemingly minor change to defining routes is actually very important for Angular 2 migration capability, but also important in Angular 1.5 to better encapsulate a template and controller at the component level.

Angular 1 actually has two router modules, ngRoute and ngComponentRouter. Only ngComponentRouter supports components, but it is also deprecated. I think the best bet is to go with ui-router.

Stateful Components

Most of the unique components you’ll build for your application are stateful. This is where you’ll actually put your application business logic, make HTTP requests, handle forms, and other stateful tasks. These components are likely unique to your application, and they focus on maintaining data over visual presentation.

Imagine you have a controller that loads a user’s profile data to display, and has a corresponding template (not shown here) linked together in a directive. This snippet might be the most basic controller to accomplish the job.

.controller('ProfileCtrl', function ($scope, $http) {
  $http.get('/api/profile').then(function (data) {
    $scope.profile = data;
  });
})
.directive('profile', function() {
  return {
    templateUrl: 'views/profile.html',
    controller: 'ProfileCtrl'
  }
})

With components, you can design this better than before. Ideally, you would also use a service instead of $http directly in the controller.

.component('profile', {
  templateUrl: 'views/profile.html',
  controller: function($http) {
    var vm = this;
    // Called when component is ready, see below
    vm.$onInit = function() {
      $http.get('/api/profile').then(function (data) {
        vm.profile = data;
      });
    };
  }
})

Now you have a component that loads its own data, thus making it stateful. These types of components are similar to routing components, except they might be used without being linked to a single route.

Stateful components will use other (stateless) components to actually render out the UI. Also, you’ll still want to use services instead of putting data access logic directly in the controller.

Stateless Components

Stateless components are focused on rendering without managing business logic, and need not be unique to any particular application. For exampe most components that are used for UI elements (such as form controls, cards, etc) don’t also handle logic like loading data or saving a form. They are intended to be highly modular, reusable, and isolated.

A stateless component may not need a controller, if it just displays data or controls everything in the template. They will accept input from a stateful component. This example takes a value from the stateful component (the profile example above) and displays an avatar.

.component('avatar', {
  template: '<img ng-src="http://example.com/images/{{vm.username}}.png" />',
  bindings: {
    username: '<'
  },
  controllerAs: 'vm'
})

To use it, the stateful component would pass the username via the attribute like so <avatar username="vm.profile.username">.

Most libraries you use are a collection of stateless components (and perhaps services). They certainly can accept configuration to modify their behavior, but they are not meant to be in charge of logic outside of their own.

Components Should Use One-way Bindings

This is not a new feature with components, but it is often smart to leverage it with components. The intent of one-way bindings is to avoid loading more work into the digest cycle, which is a major factor in application performance. Data now flows into the component without having to look outside of it (which causes some of the coupling problems that exist today), and the component can simply render itself given that input. This design also lends itself to Angular 2, which helps with future migration.

In this example, the title property is only bound into the component once based on the initial value provided. If the title changes by some outside actor, it does not get reflected in the component. The syntax to denote a binding as one-way is to use the < symbol.

bindings: {
  title: '<'
}

The component will still update when the title property changes, and we’ll cover how to listen for changes to the title property. It is recommended to use one-way anytime you can.

Components Should Consider One-time Bindings

Angular also has the ability to bind data one-time, so you can optimize the digest cycle. Essentially, Angular will wait until the first value that is not undefined is provided into the binding, bind that value, and then (once all bindings have resolved) remove the associated watchers from the digest cycle. This means that particular binding will not add any processing time to the future digest loops.

This is done by putting :: in front of a binding expression. This only makes sense if you know that the input binding will not change over the lifecycle. In this example, if title is a one-way binding, it will continue to be updated inside of the component but the binding here will not update because we denoted it as one-time.

<h1>{{::title}}</h1>

Components Should Use Lifecycle Events

You probably noticed the $onInit function as a new capability. Components have a lifecycle with corresponding events that you should be using to help manage certain aspects of the component.

$onInit()

The first step in the component lifecycle is initialization. This event runs after the controller and bindings are initialized. You should almost always use this method to do component setup or initialization. It will ensure that all values are available to the component before running. If you were to access binding values in the controller directly there is no guarantee those values will be available to you.

controller: function() {
  var vm = this;
  console.log(vm.title); // May not yet be available!
  vm.$onInit = function() {
    console.log(vm.title); // Guaranteed to be available!
  }
}

The next step is linking any child elements from the template. When the component initializes, there is no guarantee it will have also rendered any children used inside of your template. This is important if you need to manipulate the DOM in any way. One important caveat is that templates that are loaded asynchronously might not have loaded by the time this event fires. You can always use a template caching solution to ensure that templates are always available.

controller: function() {
  var vm = this;
  vm.$postLink = function() {
    // Usually safe to do DOM manipulation
  }
}

$onChanges()

While the component is active, it may need to react to changes in input values. One-way bindings will still update your component, but we have a new $onChanges event binding to listen for when the inputs change.

For this sample, imagine there is a product title and description provided to a component. You can detect changes as demonstrated below. You are able to look at the object passed to the function, which has an object mapped to the available bindings with both the current and previous values.

bindings: {
  title: '<'
},
controller: function() {
  var vm = this;
  vm.$onChanges = function($event) {
    console.log($event.title.currentValue); // Get updated value
    console.log($event.title.previousValue); // Get previous value
  }
}

$onDestroy()

The final phase is the removal of the component from the page. This event runs right before the controller and its scope are destroyed. It is important to clean up anything that your component might have created or that holds memory, such as event listeners, watchers, or additional DOM elements.

controller: function() {
  var vm = this;
  vm.$onDestroy = function() {
    // Reset or remove any event listeners or watchers
  }
}

Components Should Have a Well Defined API

To configure and initialize a component with a set of data, a component should use bindings to accept these values. This is sometimes thought of as the component API, which is just a different way of describing the way a component accepts inputs.

The challenge here is to give bindings concise but clear names. Sometimes developers try to shorten names to be really succinct, but this is dangerous for the usage of the component. Imagine we have a component that accepts a stock symbol as input, which of these two are better?

bindings: {
  smb: '<',
  symbol: '<'
}

Hopefully you thought symbol was better. Sometimes developers also like to prefix components and bindings as a way to avoid name collisions. Prefixing the components is sensible, like md-toolbar is a Material toolbar, but prefixing all of the bindings gets verbose and should be avoided.

Components Should Emit Events

In order to communicate with other components, components should emit custom events. There are many examples of using a service and two-way data binding to sync data between components, but events are a better design choice. Events are far more efficient as a means to communicate with the page (and a foundational part of the JavaScript language and the way it works in Angular 2, which is not a coincidence).

Events in Angular can use either $emit (up the scope tree) or $broadcast (down the scope tree). Here is a quick example of events in action.

controller: function($scope, $rootScope) {
  var vm = this;
  vm.$onInit = function() {
    // Emits an event up to parents
    $scope.$emit('componentOnInit');
  };
  vm.$onDestroy = function() {
    // Emits an down child tree, from root
    $rootScope.$broadcast('componentOnDestroy');
  };
}

There are two primary situations where you will need to communicate between components: between components you know about, and components you don’t. To illustrate the difference, let’s imagine we have a set of components that help manage tabs on the page, and a toolbar that has a link to the corresponding help page.

<my-toolbar></my-toolbar>
<my-tabs>
  <my-tab title="Description"></my-tab>
  <my-tab title="Reviews"></my-tab>
  <my-tab title="Support"></my-tab>
</my-tabs>

In this situation, the my-tabs and my-tab components are likely aware of one another, because they work together to create a set of three different tabs. However, the my-toolbar component is outside of their awareness.

Whenever a different tab is selected (which would be an even on the my-tab component instance), the my-tabs component needs to be aware so it can adjust the display of the tabs to show that instance. The my-tab component can emit an event up to the parent my-tabs component. This type of communication is like an internal communication between two components that work together to make a single capability (a tabbed interface).

However, what if my-toolbar wants to know what tab is currently selected so it can change the help button based on what is visible? The my-tab event will never reach my-toolbar because it is not a parent. So another option is to use the $rootScope to emit the event down the entire component tree, which allows any component to listen and react. The potential downfall here is that your event now reaches every controller, and if another component uses the same event name you could trigger unintended effects.

Decide which of these approaches make sense for your use case, but anytime another component might need to know about an event you’ll likely want to use the second option to emit to the entire component tree.

Summary

Angular 1 applications can now be written with components, which changes the best practices and nature of how we write applications. This is for the better, but just simply using a component doesn’t necessarily make it better than what you had before. Here are the key things to keep in mind as you build your Angular 1 components.

  • Isolate your logic. Keep as much of the component logic internal and away from other aspects of the application to ensure consistency and quality.
  • Keep components simple and focused on a single role. They might be complex components, but the various tasks of a single component should be logically connected as a unit.
  • Use the lifecycle events. By hooking into the component lifecycle, you can ensure that data is ready at the right time and that you can clean up.
  • Use one-way and one-time bindings. When possible, one-way bindings are more efficient and promote good design, while one-time bindings can speed up your application. You can always use $onChanges lifecycle event to watch changes.
  • Use events for communication. Components can communicate using custom events, which is in line with how Angular 2 functions and a better design.
  • Have a well defined API. Ensure that your components are clearly named and easy to understand.

Are you using components in your Angular 1.x applications? Or, are you going to wait until you make the jump to Angular 2 instead? I’d love to hear about your experiences in the comments below.

  • typo? ” for one way binding?

    • Yes, I will be fixing this.

    • Nilson Jacques

      Thanks, the article has been updated.

  • Concerned Citizen

    I like being able to link directly to a component, but afaik this is only available in the 1.0 beta versions. Unfortunately, ui-router changed so much in 1.0 that I’d have to go through my entire code base and migrate things that used $stateChange*, $viewContentLoading, etc. over to the 1.0 equivalents. That alone isn’t a big deal but it makes me worry about the changes that I don’t know about that won’t work.

    For now, I’m using sticking with ui-router 0.3.1 and call my components by putting html that calls the component in the template property and just leaving out the controller property:

    $stateProvider.state(‘mystate’, {
    url: ‘/’,
    template: ”
    });

    Same effect, just not using the new snazzy ‘component’ property.

  • zenw0lf

    Two things:

    In this part:
    “In this example, the title property is only bound into the component once based on the initial value provided. If the title changes by some outside actor, it does not get reflected in the component.” You should mention the $onChanges method as a solution for that. I know it’s below, but it’s good practice to not let your readers clueless about it.

    Two: You have a typo in all your one-way data bindings, it should be: ‘<'.

  • ExpertSystem

    Well said :) Nice article! Touches on a lot of Angular component aspects.
    A couple of thoughts/remarks:

    > Only ngComponentRouter supports components, but it is also deprecated.

    It is possible (and encouraged) to use components with `ngRoute` too (via the `template` property). See https://docs.angularjs.org/guide/component#components-as-route-templates.

    It was a deliberate choice to not only support components via `template`, because it is more idiomatic and straightforward and yet equally powerful.

    The main point is: You can (and should) use components for routing with `ngRoute`.

    – – –
    > You can always use a template caching solution to ensure that templates are always available.

    Any time you use `templateUrl` (regardless if the referenced template is in the cache or not), directive compiling/linking becomes asynchronous (i.e. it will happen *after* the parent directive has been linked).

    If you know the template is cached, you can work around this by using a `template` function that retrieves the template from the `$templateCache` synchronously, of course.

    – – –
    > One-way data binding […] no longer hook into and add load to the standard digest cycle.

    That’s not actually true. They do, but the usually impose a much smaller overhead to the digest cycle.

    – – –
    > Sometimes, two way binding still makes sense, such as form inputs.

    Totally possible, but if one chooses to embrace a one-way data flow, they can also use one-way bindings and component events/outputs (via `&` bindings).

    – – –
    > Events are far more efficient as a means to communicate with the page ([…] and the way it works in Angular 2 […]).

    Actually, Angular 2 does not use events similar to `$emit`/`$broadcast`. They use component outputs (which are basically event-emitters), which parent components can hook into.

    In Angular 1 it is similar to using `&` bindings (and this is also how `ngUpgrade` emulates component outputs for example).

  • tia howell

    Well worth your time – excellent info

  • Alex Shnayder

    Services are problematic because they hurt reuse, if you need to have more than one instance of your set of components on a screen than those sets when using service to share data can interfere with each other.

    That said I would prefer using call backs in components api if need to communicate between parent and direct child component.
    Or if there are other components in between can use require to reference parent component directly.

    I think events are problematic as there is no clear way to express them in api

  • There is always a lot to consider when choosing the right method, and events are favored because of their natural properties as part of the JavaScript language. Services are great in many ways, but if your components are truly isolated from one another a service becomes an unnecessary dependency.

    There is certainly some lost value in events from the perspective of a clear API, I certainly agree there. However, good documentation and following conventions can go a long ways to addressing this concern.

  • I don’t even discuss on time bindings, as they are not component specific, but the point I intended to drive is that with one way bindings you don’t mutate state inside of the localModel. Just because you can, doesn’t make it a good practice.

    • Alex Stanbury

      Your section ‘Components Should Use One-way Bindings’ describes one-time bindings, not one-way bindings, even though you also seem to think you are talking about one-way bindings by your use of the ‘<' symbol, which you still haven't corrected. I think you should probably have someone proof read your articles before publishing them.

      • Nilson Jacques

        Hey Alex, thanks for the feedback. The article has been updated to clarify the distinction between one-way and one-time bindings.

  • This article has been reposted without credits (and with errors) here:
    https://codequs.com/p/rksoSEKTkg/angularjs-tutorial-building-quality-angular-1-5-components/

    • Nilson Jacques

      Thanks for the heads up, @Neonjack:disqus!

  • Benjamin S.

    Hello,

    in your “my-tabs” example you explained the problem with my-toolbar but I don’t see the solution to that problem. You suddenly end the topic with:

    “Decide which of these approaches make sense for your use case, but
    anytime another component might need to know about an event you’ll
    likely want to use the second option to emit to the entire component
    tree.”

    So how can “my-tabs” communicate with “my-toolbar” without using a service?

  • Vadim

    instanciation, instead of instantiation

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.