Angular.js

Angular.js Components Example

One of the most powerful features in AngularJS are directives, what with them marking a DOM element so that it behaves a certain way. However, properly using and constructing them would give us a more robust application, as directives are essential in creating flexible Javascript and template code for our app.

With the feature-set that AngularJS has to offer, we can construct robust and flexible directives in our application by treating directives as if they are standalone, isolated components. Let’s see how can we go from directives to components in order to make app-miracles happen.
 
 
 
 

1. What are components?

Why are we, all of a sudden calling directives by the name components? They’re not the same thing, not exactly. A directive is a feature all by itself, while a component is a piece of code that can be plugged into another body of code and be expected to behave as we want it to. To put it simply, a directive is a component that works off of the inputs given and it can be used in any template anywhere and uses a simpler configuration which is suitable for a component-based application structure.

By definition, an AngularJS Component is a special kind of directive that uses a simpler configuration, suitable for a component-based application structure. This way we have it remarkably easier to write an app in a way similar to using Web Components, or Angular 2’s style of application structure. Like everything else, it has a number of advantages and also disadvantages. Let’s see them one by one!

1.1 Advantages of Components

Components are recently gaining so much momentum for a number of reasons. One of the most important ones is that components are easier than plain directives to get configured. They are under the wing of q number of programmers because they promote best practices and default pieces of code that make life easier for a lot of us. Components are optimized for the emerging application architecture that is heavily based on components, and using them will make the transition to Angular 2 much more seamless.

1.2 Disadvantages of Components

There are, however, some cases when the usage of Components is not recommended. These include: directives that rely on DOM manipulation and adding event listeners, since the compile and link functions are unavailable. Another example of when not to use Components would be when you need advanced directive definition options like priority, terminal, multi-element or when you want a directive that is triggered by an attribute or CSS class, rather than an element. Nonetheless, if you correctly pick your battles and use Components as a feature of your app, it could make you all-powerful.

2. Creating and configuring a Component

Even though people are talking about components a lot lately, most of the existing Angular code in the world is still not component-based. Components didn’t become widespread until quite recently, and many of us are working with apps that have several years of history behind them. The foundations for these codebases were laid way before components were added to our collective toolbox. Nonetheless, it is quite easy to create and configure Components, and the basis for that is the method .component().

But what is the role of .component()? This method is a simple one that takes two arguments: the name of the Component as a string and the config object, which distinctly from .directive(), cannot be a factory function. .component()‘s main role is to declare new HTML via a template or templateUrl, and it’s to be used as a creator of Components in a component-based architecture. For more, let’s see them in action!

Components, even though they might be classified as a special case of directives, can’t be more than elements. That means they are restricted 'E' and this is not optional. The code snippet below shows us how the HTML part of our code would go:

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular Components</title>


    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script src="index.js"></script>
    <script src="eraDetail.js"></script>



</head>
<body ng-app="ourApp">

<div ng-controller="MainCtrl as ctrl">
    <b>Me</b><br>
    <era-detail era="ctrl.era"></era-detail>
</div>

</body>
</html>

It’s mostly a standard structure of a main HTML document, where we notice at a first glance, that we have scripted two Javascript files, named index.js and eraDetail.js, both of which contain code parts that we will explain later on in more detail. Then, we notice that the whole body section of our document is made into an Angular app, named ourApp. After that we see that we have a div managed by the controller MainCtrl, inside of which we have placed an HTML document which appears to have been named <era-detail>. What is this element that we’ve never seen before? This, ladies and gents, is our component!

But what does this component do, what do it’s responsibilities entail? Take a look at the code below:

eraDetail.html

<span>Name: {{$ctrl.era.name}}</span>

This line of code, which you’ll notice that we have placed in a separate HTML file, is all what our Component as a DOM element will include. That is, a simple span element with an Angular binding expression, which will make more sense after we take a look at the Javascript part of our app. so let’s get right to it, then:

index.js

(function(angular) {
  'use strict';
angular.module('ourApp', []).controller('MainCtrl', function MainCtrl() {
  this.era = {
    name: 'Era'
  };
});
})(window.angular);

By using this piece of code, we have created an Angular module named ourApp, as you’ll remember from the first file we showed you. Right after that we have created a controller named MainCtrl, which contains a simple object named era, which has an attribute called name withe the given value Era. See anything familiar? Yes, it is the same variable you see in the binding of the component’s content file. But this is not all, as we need to do the configuration of the Component. We have placed that code into a separate file, which you’ve seen scripted into the main HMTL file. It’s contents would look like below:

eraDetail.js

(function(angular) {
  'use strict';
function EraDetailController() {

}

angular.module('ourApp').component('eraDetail', {
  templateUrl: 'eraDetail.html',
  controller: EraDetailController,
  bindings: {
    era: '='
  }
});
})(window.angular);

With this piece of code we create and configure our component. You seen that we have used the component() method, with it’s first argument the name of our Component. Even though you see it here as eraDetail, you use it as <era-detail> in the main HTML file, because Angular does the conversion of the cases on it’s own. The second argument to the component() method would be the config object. We use templateUrl, which would contain the path to the file containing the contents of our Component. Also, our component should have it’s own controller, in our case named as EraDetailController and lastly, special bindings. With this, we now have a fully functioning Angular component, ready to use and reuse according to our needs.

3. Components Vs. Directives

As Components are a honorary special case of directives, there are many similarities and differences between both of them. Let’s count some of them out!

First, while directives do not allow bindings, Controllers do, and bind to the controller. On the other hand, Directives do have bindToController, while for components, you’d have to perform this using regular bindings. Another main difference is that while directives have compile functions, components do not, which is one of the reasons we can’t use directives when adding event listeners, or when we have to do with elements that require DOM manipulation. The same goes for link functions.

While restriction of usage is one of the key elements for the configuration of directives, this is invalid for components since we are aware from the get-go that we can only use them as elements. We use template and templateUrl with both of them, however with Components, they’re also injectable.

4. Download the source code

This was an example of Angular Components.

Download
You can download the full source code of this example here: Components

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button