Overview Of Component In Angular 2 - Day Two

This is the second part of this series. Today, we will learn about the components. If you have not read the previous article, then kindly refer to Angular 2-Day1 (Introduction to Angular 2)

Introduction

In Angular2 “everything is components”. Using the components, we can define the elements and logics for the pages. The component is classed with the template and deals with the View of Application and it contains the core logic for the page. The components are similar to the controller of Angular 1.x . In the components, we define the code that is used in Views. The component knows how to render itself and configure Dependency Injection.


In Angular2, the components are similar to the combination of “Controller” and “Template Directives” of Angular 1. Let’s confirm this statement. Now, open your index.html page. In this page, you will find the line of code given below.


In the code given above “<app-root>” defines that we want to use the the components. Now, open “app.components.ts” file. Here, we find the definition for “app-root” component.


@Component is  meta data, which defines the code as the components. In this component, we have the property given below.

  • Selector- Defines selector for the directive.
  • templateUrl- Defines the template for the component. It is similar to template Directives of Angular 1.x.
  • styleUrls- Defines style for the template.
  • AppComponent- Similar to the controller, we define the code that can be used in our template Directives.

The components are combined form of controller and Directive templates, so here “templateUrl” is a template Directive and “class AppCompnent” works as controller, where we put our logic for the view.

Selectors

Selector is the most important part of the component, a selector tells you how you can use that particular component in view.


Now, go to your “app.components.ts” file and check the value of “selector” property of the component. Here, the value of the selector property is “app-root” that denotes selector as a “element”. It means, if you want to use the component, then you should define “app-root” as an element.


In index.html page, we are using component as an element. Let’s try to use this component as the attribute. Now, make some changes in index. Html file and refresh your page in the Browser.


When you run it, refresh your Browser and you will get the result, as shown below.


Why am I not getting the desired result? Let’s  check it out. Press “F12” and see console section. Here, find an error that “The selector "app-root" did not match any elements”. It means Angular doesn’t find any attribute that can match “app-root”.


For successful execution, change the selector type for this component. Now, in “app.components.ts” file, change the selector of the component, as shown below.


Now, when you refresh your Browser again, you will not get any error and get the desired result.


Add a new Component

Now, we will  learn how to create a new component and make configuration for this component in our application. Click View and select “Integrated Terminal” option.


In will open a command prompt Window for this app. Now, write “ng generate component firstComponent” command. This command will generate a new component for our application.


Now, check the structure of your project. Here, you will find a new directory “first-component” has been created. In this directory, you will find all the required files.


Code of first-component 

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-first-component',  
  5.   templateUrl: './first-component.component.html',  
  6.   styleUrls: ['./first-component.component.css']  
  7. })  
  8. export class FirstComponentComponent implements OnInit {  
  9.   
  10.   constructor() { }  
  11.   
  12.   ngOnInit() {  
  13.   }  
  14.   
  15. }   

In the code given above, we can see that if we want to use this component, then we need to use the “app-first-component” selector. Let’s add this selector in our HTML file.


Template code for first-component

Now, open template file for “first-component” and edit the text, as shown below.


Now, the last thing that remains is to bootstrap this component. To bootstrap this component, go to module.ts file and add the reference of “first-component” component in bootstrap property.


When the Browser refreshes, we get the result given below.


Add component in another component

In the previous example, we added the “first-component” in index.html page, but we can also use a component in another component. Now, we use “first-component” in template file of the “app.component”.

Add the code given below in “app.component” file. 

  1. <h3>  
  2. My Name is {{name}} <br/>  
  3.  I live in {{city}}  
  4. </h3>  
  5.   
  6. <app-first-component></app-first-component>  

We added “first-component” in template of “app.component”, so we don’t need to bootstrap this component. Thus, remove “FirstComponentComponent” reference from “app.module” file.


 After these changes, when the Browser will refresh, we get the same result, as shown in the previous example.


Another method to generate a component

In the previous example, we use the “ng generate component firstComponent” command to create a new component, but what if we want to generate a sibling inline component of “firstcomponent”. If we use “ng generate component secondComponent” command, then it will generate a directory and another style, template and test file. Now, we use another command to create a sibling component that contains the template and style in an inline manner.

First, open the command prompt Window in your project and move to “first-component” folder and run “ng generate component second --flat -it –is”. In this command “flat” keyword denotes that we don’t want to generate a new folder for this component, create this component in the parent directory and it stands for inline template and inline style.


This command adds a new component in “first-component” folder and this component contains the data given below.


Now, we use this component in the template file of the “first-component”, as shown below.


When you refresh the Browser, you will get the results given below.


Component life cycle

Angular2 maintains a life cycle for each component. In this life cycle, the component passes through several stages and at each stage Angular performs some specific task. A component life cycle contains the stages given below.
Image source: Google

A component goes through above stages from top to down order. In each stage, the component performs some specific tasks. The list given below shows that Angular performs in each stage.

StageTask
ConstructorInvoked when Angular creates a component or Directive by new. This method is executed before the execution of any one life cycle method.
ngOnChangesCalled when value of input controller of binding the data changes.
ngOnInitOn component initialization, after first ngOnChanges
ngDoCheckDuring every Angular 2, change detection cycle
ngAfterContentInitThis method executes after the component content is initialized.
ngAfterContentCheckedAfter every check of inserted component content
ngAfterViewInitExecutes after component views initialize
ngAfterViewCheckedExecutes after every check of component views
ngOnDestroyExecutes before the component destroys.

Let’s take an example of the component life cycle. Add a new component named  “lifeyCycle”, using “ng generate component lifeyCycle” command.


Add the code given below in your “lifey-cycle.components.ts” file. 

  1. import { Component, OnInit,OnChanges,DoCheck,AfterContentInit,AfterContentChecked,  
  2. AfterViewInit,AfterViewChecked,OnDestroy } from '@angular/core';  
  3.   
  4. @Component({  
  5.   selector: 'app-lifey-cycle',  
  6.   templateUrl: './lifey-cycle.component.html',  
  7.   styleUrls: ['./lifey-cycle.component.css']  
  8. })  
  9. export class LifeyCycleComponent implements OnInit,OnChanges,DoCheck,AfterContentInit,AfterContentChecked,  
  10. AfterViewInit,AfterViewChecked,OnDestroy  {  
  11.   
  12.   constructor() { }  
  13. ngOnInit(){  
  14.   console.log('OnInit');  
  15. }  
  16.   
  17. ngOnChanges(){  
  18.   console.log('OnChanges');  
  19. }  
  20.   
  21. ngDoCheck(){  
  22.   console.log('DoCheck');  
  23. }  
  24.   
  25. ngAfterContentInit(){  
  26.   console.log('AfterContentInit');  
  27. }  
  28. ngAfterContentChecked(){  
  29.   console.log('AfterContentChecked');  
  30. }  
  31. ngAfterViewInit(){  
  32.   console.log('AfterViewInit');  
  33. }  
  34. ngAfterViewChecked(){  
  35.   console.log('AfterViewChecked');  
  36. }  
  37.  ngOnDestroy(){  
  38.    console.log('OnDestroy');  
  39.  }   
  40.   
  41. }   

In the code given above, we import all the life cycle hooks and implement there corresponding interfaces in “LifeyCycleComponent” class.

Now, add the “app-lifey-cycle” component in “app.component.html” file.


Now, refresh your Browser, check the console and you will get the output given below.

You can see that in first cycle component, it goes through the 6 phases. In this cycle, we don’t get “ngOnChanges” because we don’t bind any values and we also don’t get “ngOnDestroy” phase because till now our component is not destroyed.


Example of OnDestroy phase

In the previous example, we get 6 phases of Angular component life hook. Now, we take an example for OnDestory. Add the code given below in “lifey-cycle.component.ts” file.


Now, make the changes given below in “app.component.html” file. 

  1. <h3>  
  2.    My Name is {{name}} <br/>  
  3.     I live in {{city}}  
  4. </h3>  
  5.   
  6. <app-first-component></app-first-component>  
  7.   
  8. <app-lifey-cycle *ngIf="!value" ></app-lifey-cycle>  
  9.   
  10.   <button (click)="value=true">Change Value</button>   

Now refresh your browser, when page loads it will show the following result.


Now, click on “Change Value” button and examine the result.


When we click on “Change Value” button ,statement *ngIf="!value", it returns false, so “app-lifey-cycle “ component will be destroyed and now “Ondestory” event will call page.

Conclusion

In this article, we learned about the component in Angular 2. If you have any queries, then write them in the comment section. In the next article, I will cover another topic of Angular 2.

Thanks for reading the article.

Up Next
    Ebook Download
    View all
    Learn
    View all