AngularJS 2.0 From Beginning - Component - Day Two

I am here to continue the discussion around AngularJS 2.0. Today, we will discuss about Component in AngularJS 2. Also, in case you did not have a look at our previous articles of this series, go through the links, mentioned below.

In this article, we will cover the topics about component, as shown below.

  1. What is component.
  2. How to create a component.
  3. About component function properties or argument.
  4. Life Cycle of the component.
  5. Nested component.

In my previous article, I discussed how to write a simple "Hello World" type program in Angular2. In that program, we developed a component class named FirstProgComponent with the @component decorator. Actually, component is the main building block of Angular2 Framework. In Angular2 application project, any number of components can be created and used within a single HTML file. Basically, Angular2 framework is a component based framework, which is the main difference from the previous version of AngularJS.

Actually, previous versions of AngularJS are based on the concept of controller and directives to populate the data and also responsible to develop any custom elements for the view but in Angular 2, components perform all the responsibilities that are performed by controllers and directives.

What is component ?
 
In Angular2, every thing is component. Component is the main building block of Angular2 framework. Basically, component is the main process in which we can define or design the views including the logic.

Steps to create a component

Although, we have already created our first component in the previous article. But in spite of that, I describe the steps for creating a component.
  1. Create a typescript base class and export it. As it is very much clear from its name that export keyword is used to export any type of objects like class, functions etc. from an angular module. Export is basically just an identifier, which indicates that it can be import into any other script section, using import keyword or module in Angular2. Export or import both the modules are supported by ES6 module definitions.

  2. Now, decorate the class with @component metadata decorator or annotations. Basically @component add some metadata to the class objects in order to provide some specific meaning. Basically, it is the declarative way to add metadata to the code.

    Now, the first questions arise that where the @component is defined? As we all know, it is not a JavaScript keyword or method. The answer is that this keyword is provided by Angular2 framework itself. Basically Angular2 framework provides us some inbuild module or provider for the perform our task. For use @component decorator or annotation in our class, we need to import the
    code module into our class file at the beginning.

    import {component} from ‘@angular/core’

  3. Import the required library or module to develop the component.

  4. Now, include the component class within the ngModule in order it to be used by other component or Applications. To mention that component is a member of ngModule, you need to add the component name within the declaration field of ngModule.

Component Configuration

@Component decorator basically decorated a type script class as a component objects. Basically, it is a function, which takes different types of parameters. In the @component decorator, we can set the values of different properties to finalize the behavior of the components. The most used properties are shown below.

  1. selector
    A component can be used by the selector expression.

  2. template
    Basically, template is the part of the component, which is rendered in the Browser. We can directly define HTML tags or code within the template properties. Sometimes we called this as an inline template. For writing multiple lines of HTML code, all code need to be covered within tilt (`) symbol.

  3. templateUrl
    Another way of rendered HTML tags in the Browser. Here, we need to provide the HTML file name with its related file path. Some times, it is known as external template. It is better approach, if HTML is a part of the component is complex.

  4. moduleId
    It is used to resolve the related path of the template URL or style URL for the component objects.

  5. styles or stylesUrls
    Component can use its own style by providing custom CSS or can refer to an external style sheet files, which can be used by multiple components at a time. For proving inline style, we need to use styles and to provide external file path or URL, we need to use styleUrl's.

  6. providers
    We are in the real life Application. We need to use or inject different types of custom Service within the component to implement the business logic for the component. To use any custom Service within the component, we need to provide the Service instance within the provider. Basically, provider is an array type property, where multiple Service instance name can be provided by comma separation.

Life Cycles of the Component

The life cycle of the component is maintained by Angular2 himself. Below is the list of life cycle method of Angular2 components.

  • constructor
    This method is executed before the execution of any one life cycle method. It is basically used for inject dependency.

  • ngOnChanges
    This method is called when an input control or binding value changes.

  • ngOnInit
    This method is called after the execution of first ngOnChnages.

  • ngDoCheck
    This method is called after every execution of ngOnChnages.

  • ngAfterContentInit
    This method executes after component content is initialized.

  • ngAfterContentChecked
    This method is executed after every check of the component check.

  • ngAfterViewInit
    This method executes after component views initialize.

  • ngAfterViewChecked
    This method executes after every check of component views.

  • ngOnDestroy
    This method executes before the component destroys.

Now, to create a component, first create a typescript file named app.component.template.ts and add the code, mentioned within it.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. @Component({  
  5.     moduleId: module.id,  
  6.     selector: 'hello-world',  
  7.     templateUrl: 'app.component.template.html',  
  8.     styles: ['h1{color:red}']  
  9. })  
  10. export class TemplateComponent {  
  11.     message: string = "Angular 2 Component with Template";  
  12.     author: string = "Debasis Saha";  
  13.     constructor() {}  
  14. }  
In the code, mentioned above, I use template URL and style to show the text in different color. Now, for template HTML file, add HTML file named app.component.template.HTML and add the code, mentioned below.
  1. <div>  
  2.     <h1>{{message}}</h1> <br />  
  3.     <h2>{{author}}</h2>  
  4. </div>  
Now, run the code and the output is mentioned below.

Angular 2

In the example, mentioned above, I set the color of h1 tag as Red. Thus, when I run the code in the Browser, it will effect automatically. The same thing can be done by providing the style code within a CSS file and provide the file name with the relative file path to import the style class into the document.

Nested Component

Just like previous version of AngularJS, Angular2 also allows us to create nested component or component inside a component.

Let's see how it works. I first create a component called parentcomponent. Now, I also create two separate components named childComponent and EmailBoxComponent. Now, I want to use these two components within the parent component template. For doing this, I need to do the following.
  • Import childcomponent and EmailBoxComponent within ngModule.
  • Include the component name within declaration property of the ngmodule.
  • Use child component, using their selector in the parent component template.

To demonstrate the nested component, I first create two child components. One of them simply displays some fixed text message within h2 tag. The another child component will be a simple search button with textbox. For doing this, we need to add one TypeScript file named as "app.component.child.ts" and write down the code, mentioned below.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. @Component({  
  5.     selector: 'child',  
  6.     template: '<h2>{{message}}</h3>'  
  7. })  
  8. export class ChildComponent {  
  9.     message: string = "This is Child Component";  
  10.     constructor() {}  
  11. }  
Now, add another TypeScript file with name "app.component.emailbox.ts" and write down the code, mentioned below.
  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. @Component({  
  5.     selector: 'email-box',  
  6.     template: '<input placeholder="Email"/><button class="btn-clear">Register</button>'  
  7. })  
  8. export class EmailBoxComponent {}  
Now, create another TypeScript file named as "app.component.parent.ts" and add the code, mentioned below.
  1. //components files   
  2. import {  
  3.     Component,  
  4.     OnInit  
  5. } from '@angular/core';  
  6. //   
  7. @Component({  
  8.     moduleId: module.id,  
  9.     selector: 'my-app',  
  10.     templateUrl: 'app.component.parent.html',  
  11. })  
  12. export class ParentComponent implements OnInit {  
  13.     constructor() {}  
  14.     ngOnInit() {}  
  15. }  
Now, create another HTML file named as "app.component.parent.html" and the add the code, mentioned below.
  1. <div>  
  2.     <h1>This is Main Component</h1> <br />  
  3.     <child></child>  
  4.     <child></child>  
  5.     <child></child> <br />  
  6.     <email-box></email-box>  
  7. </div>  
Now, add another TypeScript file for module with name "app.module.ts" and write down the code, mentioned below.

  1. import
     {  
  2.     NgModule  
  3. } from '@angular/core';  
  4. import {  
  5.     BrowserModule  
  6. } from '@angular/platform-browser';  
  7. import {  
  8.     ParentComponent  
  9. } from './src/app.component.parent';  
  10. import {  
  11.     ChildComponent  
  12. } from './src/app.component.child';  
  13. import {  
  14.     EmailBoxComponent  
  15. } from './src/app.component.emailbox';  
  16. @NgModule({  
  17.     imports: [BrowserModule],  
  18.     declarations: [ParentComponent, ChildComponent, EmailBoxComponent],  
  19.     bootstrap: [ParentComponent]  
  20. })  
  21. export class AppModule {}  
Output
 
Now, run the code. The output is shown below. 

Angular 2


Similar Articles