Learning Angular - Lab Two


This lab is continuation of the Angular 2 learning series.

We are going to learn the basic building blocks of Angular2 web application which are Components.

Please go through my previous labs on Angular 2 to set up the project and learn Angular 2 easily.

Angular Components

In Angular 2, everything is a component.

Components are the main way we build and specify elements and logic on the page, through both custom elements and attributes that add functionality to our existing components.

What does this mean?

Component Code

  1. import {Component} from '@angular/core';  
  3. @Component({  
  4.   selector: 'my-app',  
  5.   template: `<h1>Hello {{name}} </h1>`,  
  6. })  
  8. export class AppComponent {   
  9.     name = 'Angular';  
  10.  }  

If you analyze component code closely you will see it consists of three portions.

Section 1 - Class

  1. export class AppComponent {   
  2.     name = 'Angular';  
  3.  }  

Export key word with the class makes this class being used by other components.

Section 2 - Decorator

Here the decorator is @Component which add metadata. This decorator is provided by Angular framework and to use this section 3 is required, meaning we must import that component in appCompnenet class.

  1. @Component ({  
  2.   selector: 'my-app',  
  3.   template: `<h1>Hello {{name}} </h1>`,  
  4. })  

Component Decorator has several properties which are used to provide a way to add meta data to class.

Above we have used two properties, selector and temperate.


Selector: ‘my-app’

This property is used to define a section where my-app will be used as directive and the template html will be added to the rendering section of html.


template: `<h1>Hello {{name}} </h1>`

Basically, this is a small piece of html code with backtick character.


  1. <!DOCTYPE html>  
  2. <html>  
  3.   <head>  
  4.     <title>Angular QuickStart</title>  
  5.     <base href="/src/">  
  6.     <meta charset="UTF-8">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.     <link rel="stylesheet" href="styles.css">  
  10.     <!-- Polyfill(s) for older browsers -->  
  11.     <script src="/node_modules/core-js/client/shim.min.js"></script>  
  13.     <script src="/node_modules/zone.js/dist/zone.js"></script>  
  14.     <script src="/node_modules/systemjs/dist/system.src.js"></script>  
  16.     <script src="systemjs.config.js"></script>  
  17.     <script>  
  18.      System.import('main.js').catch(function(err){ console.error(err); });  
  19.     </script>  
  20.   </head>  
  22.   <body>  
  23.     <my-app>Loading AppComponent content here ...</my-app>  
  24.   </body>  
  25. </html>  

At run time <my-app> directive component is replaced by template code when index .html is being rendered.


Section 3 - Angular Component

Component decorator is imported from angular/core to be used as reference to be used further by appComponent class to setup meta data.

  1. import {Component} from '@angular/core';  


This is another beautiful property to reference a separate html file with all required capabilities of html. Here you can see the template is html code separated by backtick character. This is inline code.

To use templateUrl, I have added app.component.html to app folder and pointed templateUrl to html.

  1. import {Component} from '@angular/core';  
  3. @Component({  
  4.   selector: 'my-app',  
  5.   templateUrl: "app/app.component.html"  
  6. })  
  7. export class AppComponent {   
  8.     name = 'Angular v2';  
  9.  }  

Nested Component

Nesting of components meaning using component inside another component. In angular2 nesting of component help to design different functionality very easily.

Let’s take a scenario where students UI needs a search functionality where a text box and button will be there which initiate a search and refresh the students table on page with the search result.

Above is the requirement given to achieve where a search functionality needs to be there on student’s page with text box and button.

To achieve this, I am using the previous example of students list with old project.

Here by taking advantage of angular components we can easily achieve this requirement. We need to create a search component which is placed in students component.

Basically, we are nesting search component with students component which is finally injected into main app component.

Let's see in code.


  1. import {Component, NgZone,OnInit} from '@angular/core'  
  2. import {student Service } from './student.service'  
  3. import { IStudents } from './students'  
  5. @Component({  
  6.     selector: 'student-list',  
  7.     templateUrl: 'app/students/student.component.html',  
  8.     styleUrls: ['app/students/students.css']  
  9. })  
  10. export class studentComponenet implements OnInit   
  11. {  
  12.     _students: IStudents[];  
  13.     constructor(private _studentservice: studentService, private zone: NgZone)  
  14.     {        
  15.     }  
  16.     public LoadStudents(searchtext :string): void {  
  17.         this._students = this._studentservice.getStudents();  
  19.         if (searchtext != "") {  
  20.             var _studentList: any[] = [];  
  22.             this._students.forEach(student => {  
  23.                 if (student.StudentName.toLowerCase().includes(searchtext)) {  
  24.                     _studentList.push(student);  
  25.                 }  
  26.             })  
  27.             this._students = _studentList;  
  28.         }    
  29.     }  
  30.     public LoadStudentsFromService(): void {  
  32.         this._studentservice.get("http://localhost:59923/api/Students").subscribe((studentData) => this._students = studentData);  
  33.     }  
  34.     ngOnInit() {  
  35.         this.LoadStudents("");  
  37.     }    
  38.     Onclick(searchtext: string): void {  
  39.        this.LoadStudents(searchtext);  
  41.     }   
  42.     getResultCount(): number {  
  43.         return this._students.length  
  44.     }  
  45. }  


  1. <search-selector [resultCount]="getResultCount()"   (Search)="Onclick($event)"></search-selector>  
  2. <br />  
  4.     <table class="table">  
  5.         <thead>  
  6.             <tr>  
  7.                 <th>  
  8.                     Student Name   
  9.                 </th>  
  10.                 <th>  
  11.                     Gender   
  12.                 </th>  
  13.                 <th>  
  14.                     Location   
  15.                 </th>  
  16.                 <th>  
  17.                    Date of Joining   
  18.                 </th>  
  19.             </tr>  
  20.         </thead>  
  21.         <tbody>  
  22.             <tr *ngFor="let student of _students">  
  23.                 <td >{{student.StudentName}}</td>  
  24.                 <td>{{student.Gender}}</td>  
  25.                 <td>{{student.Location}}</td>  
  26.                 <td>{{student.DateOfJoining}}</td>                  
  27.             </tr>  
  28.         </tbody>  
  29.     </table>  


  1. import { Component,Input, Output, EventEmitter } from '@angular/core'  
  3. @Component({  
  4.     selector: 'search-selector',  
  5.     templateUrl:'app/Search/Search.Component.html'  
  6. })  
  7. export class searchComponent  
  8. {  
  9.     @Input() resultCount: number=10;  
  11.     @Output() Search = new EventEmitter<any>();  
  13.     Onclick(searchtext: string): void {  
  14.         this.Search.emit(searchtext);  
  15.     }  
  16. }  


  1. <div class="form-group">  
  2.   <div class="md-col-12">  
  3.     <input class="form-control" #searchText type="text" placeholder="Search Here" />   
  4.     <button type="submit" class="btn btn-default" (click)="Onclick(searchText.value)">  
  5.             Search  
  6.     </button>   
  7.   </div>  
  8.     <br />  
  9.     <div class="md-col-4">  
  10.         <b>Result Count: {{resultCount}} </b>  
  11.     </div>  
  12. </div>  

I have added four files two type script and two html files above.

In the above file Students.components.html you can see search-selector section above the html for students

  1. <search-selector [resultCount]="getResultCount()" (Search)="Onclick($event)"></search-selector>  

This is how we can register our component for nesting it another component.

Here search component is nested with student component.

Input and Output Properties for Component

You must be wondering what are @input() and @output() properties used above with searchCompoment.

@input (): Property Binding (Parent component to child Component)

@Input decorator binds a property within one component (search component) to receive a value from another component (student component).

For using @input decorator for any property and we need to import Input from angular/core.

  1. import {Component, Input, Output, EventEmitter} from '@angular/core  

Need to decorate the property with @input decorator

  1. @Input() resultCount: number=10;  

In above the result count is the number of records displayed on the child component which is being sent from parent component using input properties.

@Output: Event Binding (Child component To parent Component)

@Output decorator binds a property of a component to send user actions, data from one component (child component) to calling component (parent component). This is one way to pass data from child to parent component

For using @output decorator for any property and we need to import Output from angular/core

  1. import {Component, Input, Output, EventEmitter} from '@angular/core  
  2. @Output() Search = new EventEmitter<any> ();  
  4. Onclick(searchtext: string): void {  
  5.         this.Search.emit(searchtext);  

Here you can see Search is decorated with @Output and it make it as custom event of EventEmitter class for payload of type any.

This property name becomes custom event name for calling component

  1. <search-selector [resultCount]="getResultCount()" (Search)="Onclick($event)"></search-selector>  

Search becomes a custom event which is bound with click event of button, so whenever search button is clicked from child component which is (search functionality) , it will pass the text from child to parent as parameter and records as per the search text matching result will be displayed and the count will be sent back from parent component to child and web page is being updated.

Final Output


I have used Angular2 services in this article to fetch student’s data from WebAPI and display on the web page. In my next article, I am going to explain services in detail

Keep learning and keep smiling.

Resources and Useful Links


<<Click here for previous part