Build an Angular 1.5 component – An AngularJS tutorial

Angular 1.5 recently introduced components, a feature also available in Angular 2. Using components from and in Angular 1.x makes a lot of the sense as it will help your application bridge the gap between Angular 1.x and Angular 2, which is the main reason why the Angular team announced components availability in Angular 1.5.

What’s a component?

A component is basically a directive that uses a simpler configuration and that is suitable for a component-based architecture, which is what Angular 2 is all about.  Think of a component as a widget: A piece of HTML code that you can reuse in several different places in your web application.

Create a component

Let’s build a simple “Hello World ” component to illustrate how easy it is.  The end goal for our component will be to display this simple piece of HTML:

<span>Hello World!</span>

The syntax to create a component is fairly easy. All you have to do is declare its name and pass a config object that specifies what your component should do. In our case, it will render some basic HTML:

angular.module("myApp", [])
  .component("helloWorld",{
      template: 'Hello World!'
  });

In order to then use that component in our code, all we need is this:

<div ng-app="myApp"> 
  <hello-world> </hello-world>
</div>

You can see the end result in action with this CodePen, which you can edit as well.

Recommendation

If your company is hiring a JavaScript developer, check out this JavaScript test prepared by our professionals. It will allow you to identify the best talents very easily!

How to use external data in a component

Now let’s make our component more useful. When a single-page application is made of several different components, data is usually loaded by a service and then passed to the components that need it. In our case, we could add a parameter to pass a name to our component, which would be used as follows:

<div ng-app="myApp"> 
  <hello-world name="'John'" > </hello-world>
</div>

The end result would be:

<span>Hello John!</span>

We achieve this by defining bindings for our component. Here we basically define the name of the attribute that will be added to our component along with the type of binding we want to use. There are four different types of bindings:

  • = means that we’re using a two-way data binding. This means that if you update that variable in your component scope, the change will be reflected on the parent scope;
  • < is for one-way bindings when we just want to read a value from a parent scope and not update it;
  • @ is for string parameters;
  • & is for callbacks in case your component needs to output something to its parent scope.

In our case, we want to use a simple string so our component will look like this:

angular.module("myApp", [])
  .component("helloWorld",{
      template: 'Hello {{$ctrl.name}}!',
      bindings: { name: '@' }
  });

Note that bindings are added to the local scope of your component, which is bound to a controller called $ctrl by default. That’s the reason why our HTML template gets the value to display through the {{$ctrl.name}} expression. Here is a link to the updated CodePen for those changes.

Adding a controller to a component

Now that we know how to pass data to a component, let’s take a look at how to add a controller to it. This would be useful if, for instance, your component needs to have some Javascript code to load data from a service. Here is a basic example for our Hello World component (you can find the corresponding CodePen here):

angular.module("myApp", [])
  .component("helloWorld",{
      template: "Hello {{$ctrl.name}}, I'm {{$ctrl.myName}}!",
      bindings: { name: '@' },
      controller: function(){
        this.myName = 'Alain';
      }
  });

You do not have to define your controller locally. It is actually better to define it in a separate file and use a controller name instead of a function definition in our component definition. Note that it’s also possible to use your own controller name with the controllerAs attribute, in case you don’t like $ctrl.

Build an Angular 1.5 component – An AngularJS tutorial - Step by Step Guide with DemoClick To Tweet

What else can we do with components?

Our previous example was a very basic one, so the HTML was not very complex. Your actual components might have dozens of lines of HTML code, in which case it’s much better to have a specific HTML file for that. Then our component would just reference that HTML template as follows:

angular.module("myApp", [])
  .component("helloWorld",{
      templateUrl: "templates/helloWorld.html",
      bindings: { name: '@' }
  });

In some instances you may need to access data from a parent component inside your component. This can be achieved by specifying that our component requires that parent component, which can then be used in our controller as shown in the example below:

angular.module("myApp", [])
  .component("helloWorld",{
      template: "Hello {{$ctrl.name}}, I'm {{$ctrl.myName}}!",
      bindings: { name: '@' },
      require: {
        parent: '^parentComponent'
      },
      controller: function () {
       // use this.parent to access required Objects
       this.parent.foo();
      }
  });

Lifecycle hooks

Now you know almost everything there is to know about components. One last thing though: Angular 1.x components come with lifecycle hooks, just like their Angular 2 counterparts.

These are methods that will be called at certain points in the life of the component. The following hook methods can be implemented:

$onInit()

Called on each controller after all the controllers on an element have been constructed and had their bindings initialized. This is a good place to put initialization code for your controller.

$onChanges(changesObj)

Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form { currentValue, previousValue, isFirstChange() }

$onDestroy()

Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, watches and event handlers.

$postLink()

Called after this controller’s element and its children have been linked. This hook can be considered analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2.

Now you’re ready to write your own Angular 2 components. You can find the official documentation on the Angular website, where there are more details on the differences between directives and components.

Build an Angular 1.5 component – An AngularJS tutorial - Step by Step Guide with DemoClick To Tweet

Alain Chautard is a published Angular JS expert and organizer of the Sacramento Angular JS meetup group in California. He shares his thoughts and current projects on his website www.alainchautard.com while running his own software consultancy at www.interstate21.com

Coding skills assessment

If you're looking to hire software engineers and want to ensure that you only interview qualified candidates, we've created coding tests that can significantly simplify your hiring process:

23 Shares

  17 Comments

  1. Samad   •  

    Thanks Alain for this post.

    I’m new in angular 1.5 components. I build a multi-level grid (ng-repeat) as a component template that gets its data from a json file. the grid is expendable when the row is clicked :

    this works fine and also for nested grids. However, I m trying to implement a ng-keydown on the row as well so the user can select rows and expend them by keyboard. But it doesn’t seem to work.

    Also I tried to make it work by doing some dome manipulation on $postlink hook without success.

    Would you have an example of a working ng-keydown/ng-keypress on tr element?

    Thanks

  2. Junaid Salaat   •  

    Swift and easy to understand article. really helped. Thanks.

  3. Tilovon Crite   •  

    Hi Alain. Thanks for the tutorial. I’m new to Angular and I wanted know, do components go into 1 js file or do you need a separate js file for each component?

    Thanks

  4. Himanshu   •  

    Wonderful Article!. I was looking something into the web to clear my concepts on ‘components in Angular’, but wasn’t able to find anything good, prior to this. Now I am pretty much clear to convince the interviewer.
    Really worthwhile.

  5. Cathryn   •  

    Thank you for thee good writeup. It in fact was a amusement account it.

    Look adcanced to more added agreeable from you!
    By the way, how could we communicate?

  6. Gaurav   •  

    Thanks for getting me started with Angular 1.5 🙂

  7. MelissaPlock   •  

    whoa1h this blog is great i love reading your posts. Keep up the great work! You know, a lot of people are looking around for this information, you can aid them greatly.

  8. Helenwaymn   •  

    gaps in employment cover letter samples
    free resume templates high school graduates

  9. Gil Shapir   •  

    Very organized and simple to follow writing!

  10. K   •  

    Can we use component created in one module inside separate module? If yes, How?

  11. Plus Tuition   •  

    Excellent post. Wonderfully explained. Bring on Angular 2.

  12. vishal   •  

    very good post to understand Component part of the Angular 1.X, best so far !!

  13. free chat   •  

    Nice post. I was checking constantly this blog and I’m inspired! Very useful info particularly the closing part 🙂 I handle such information much. I used to be looking for this particular information for a very lengthy time. Thanks and good luck.

  14. Sahil   •  

    Nicely explained

  15. Vicki   •  

    If some one wishes expert view about running a blog afterward i recommend him/her to go to see this
    webpage, Keep up the nice work.

  16. Ritesh   •  

    just perfect..
    To the point and clear

  17. Miley Cyrus   •  

    Interesting article

Leave a Reply

Your email address will not be published. Required fields are marked *