Click here to Skip to main content
15,892,298 members
Articles / Programming Languages / Javascript

Build an Angular 1.5 Component – An AngularJS Tutorial

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
26 Oct 2017CPOL5 min read 14.8K   2  
Read a tutorial which allows you to build your own Angular Component! Examples and code snippets inside!

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 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:

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:

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

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

HTML
<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.

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:

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

The end result would be:

HTML
<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:

Java
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):

Java
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.

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:

Java
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:

Java
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:

Java
$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.

Java
$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() }

Java
$onDestroy()

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

Java
$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.

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

The post Build an Angular 1.5 component – An AngularJS tutorial appeared first on Tests4Geeks.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Tests4Geeks is programming skill testing service.
Besides our main business, we also produce programming tutorials which allow readers to learn new tools and languages.

Comments and Discussions

 
-- There are no messages in this forum --