The Complete Beginners Guide to Angular 2 Components

Components are Angular 2 building blocks that contain both logic and UI behavior. Components contain both HTML templates and classes. You can say that component classes are like Angular 1.x controllers.

You can compare components to an Angular 1.x directive, however, a definition of a component is one autonomic module that contains both UI and UI-oriented logic. If you are familier with Angular 1.x, you may compare a controller to a small module that contains both an HTML template and a controller, all while the exported class acts as the controller.

Components in Angular 2.0 increase the HTML element name vocabulary with the app’s components, in the same way that HTML5 web components are supported in Angular 2.0.

While building a component we will provide it with both HTML template and UI related logic. The UI related logic is on a class that we export. The class is decorated with a component decorator function that receives an object with the HTML template as one of its members.

Component Decorator

Component Decorator A component contains an exported class decorated with a component decorator. A component decorator is a function that gets a ViewMetaData typed object as a parameter.

When creating a component, we have to decorate our class with the component decorator. The component decorator is a JavaScript function that receives a component description object as a parameter. This object is of type ViewMetaData and contains the following properties:

  1. selector : The selector for the component. It can be a new HTML element name, attibute, class, etc. In most cases, the selector is set for a new HTML element name.
  2. template : an HTML markup to be rendered when the component is set.
  3. templateUrl: A URL points at an HTML file that contains the template.
  4. directives: An array of types of other components or directives used by this component.
  5. pipes: An array of pipes used by the component as pipes (See pipes later on in this chapter)
  6. Styles: An array of strings where each string is a style rule
  7. styleUrlS: A URL to an external CSS file
  8. encapsulation: The encapsulation type of the view
  9. providers: An array of types of injectable services used by the components, so whenever the component is instanciated, an instance of each provider is instanciated as well

A component is structured as follows:

import {Component} from '@angular/core'
/**
Another imports
**/ 
@Component({/*ViewMetaData object */})

export class MyCompoentClass {
}

The component template The component template may be written inside the component decorator in the ViewMetaData’s template member, or written in a seperate file while its URL is given by the templateUrl member of the ViewMetaData object.

Please note that the template URL is relative to the application root and not to the component.

ViewEncapsulation ViewEncapsulation is an enumaration used to determine how styles will be encapsulated in the component. It has three entries:

  1. Native: Use the browser’s native encapsulation mechanism. This means using Shadow DOM for the component and create a Shadow root on the component’s host element.
  2. Emulated: Emulates the native encapsulation. The emulation is done by adding a surrugate ID to the host element and preprocess the style rules given on the ViewMetaData object of the component. This is the default option and it will be used unless stated otherwise.
  3. None: No style is encapsulated for the component.

Component Usage:

Using a component is enabled by importing the component’s class, by adding the component’s selector in the suitable place in the template using the component, and by adding the component’s class to the array of directives used by the host compoents. You may add some attribute to the same hosting element to send data to the component. We will later demonstrate it in the Input/Output section in this chapter.

Using injectable services

Using injectable services

This is a component that wishes to use injectable service needs to receive it in one of its constructor’s parameters. Having the private keyword before each injectable parameter makes a class member named the same as the parameter name and assigns the parameter to it.

Providers: Having the constructor parameters doesn’t make sure that in instance will be sent to the constructor. To make sure in instance is created, we need to put the injectable service type in the providers array of the ViewMetaData .

Note: Unlike Angular 1.x services, the Injectables services are not necessarily singletons. Whenever a type of service is in a component’s providers array, an instance of it is created upon the creation of the component’s instance (i.e., it is not a singleton). It will be preferred that injectable services you wish to use as a single instance will be put in one provider’s array in the application’s main component.

The code example below demonstrates how to declare an injectable service and how to use it.

First, let’s write an injectable service:

@Injectable()
export class MyService {
/*Service code goes here*/
}

As you can see above, this is simply an exported class decorated with the Injectable decorator.

Second, let’s use it in a component:

First, we have to import the class, because we will always do this when we want our code to use code from another file:

import {MyService} from 'path/to/myService';

Second, we need to instansiate it. The Angular 2.0 framework will do that for us after we will put our service in a component’s providers array. If the service is put in the provider’s array in another component (for example, our main component), the service has to be imported there as well.

@Component({ /*some ViewMetaData members */
   providers: [ MyService],
   /*some other ViewMetaData members */ });

And, last but not least, we have to inject the service in our component’s class constructor.

export class MyCompoentClass {
 constructor(private _myService:MyService){
 }
}

By doing so we create a class member named _myService with the type of MyService, and the parameter sent to the contructor is assigned to it.

Plesae note that it creates a class member without you ddeclaring it, No additional code is needed here.

In next Chapter you will learn about Pipes ..

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares