AngularJS - Components

By xngo on August 26, 2019

In AngularJS, a directive can be turned into a reusable and isolated component. A component is basically comprised of fragments of HTML template code and a controller. It can be registered using the angular.module().component() method. This method take 2 arguments:

  • The name of the component as string in camel case (e.g. greetUser). But we will use kebab-case (e.g. greet-user) when referring to it in the HTML.
  • The component configuration object.

Create and configure component

The following code will create greetUser component. Every time that you include <greet-user>, it will display the HTML template, '<span>Hello, {{$ctrl.user}}!</span>' .

<body ng-app="myApp">
    <greet-user></greet-user>
</body>
 
<script>
myApp = angular.module('myApp', []);
myApp.component('greetUser', {
            template: '<span>Hello, {{$ctrl.username}}!</span>',
            controller: function GreetUserController() {
                    this.username = 'John';
                }
        }
    );
</script>

Output

Hello, John!

Use external template

The example above uses a simple HTML template code. However, with longer and more complex HTML template code, it will be messy to write it is as a string. AngularJS provides the templateUrl property to allow us to load the template from a file. Here is how to rewrite the same example using templateUrl.

myApp.component('greetUser', {
            template: greet-user.template.html,
            controller: function GreetUserController() {
                    this.username = 'John';
                }
        }
    );

In the greet-user.template.html file, you will put:

<span>Hello, {{$ctrl.username}}!</span>

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.