Component In Angular 2 and How to Create Nested Component in Angular 2

In the previous article about Angular 2, we covered what the pipes are and how to create the custom pipes in Angular 2. Now, in this article, we will learn about Angular 2 components and we will also see how to create a nested component and how parent and child components communicate with each other.

Angular 2 Components

We all know that Angular 2 is a component based framework because everything is a component in Angular 2. Basically, components are the basic building blocks of Angular 2 application. It also allows us to create reusable UI templates.

A component in Angular 2 is a class with a template and a decorator. There are basically the following parts of Angular 2 component –

  • Class
    It is very similar to the C# class or java class etc. It contains the constructor, variables and methods code which is required for the template/user interface.

  • Decorator
    A decorator is used to store the metadata about the class. Basically, the decorator provided by Angular makes a class an Angular component when it is decorated with the component decorator.

Angular 2 provides us basically 4 types of decorators,

  1. Class Decorators
    For Ex. @NgModule, @Component & @Directive
  1. Property Decorators
    For Ex. @Input & @Output
  1. Method Decorators
    For Ex. @HostListener
  1. Parameter Decorators
    For Ex. @Inject

I am not going to define the types of decorators here in detail. We will discuss in detail about them in later articles.

Each decorator has a basic configuration using several properties. We are taking a look at some possible configuration properties right here, that you can use when creating a component,

  1. Selector – This is used for identifying this component in templates.
  2. Template – This is used for defining HTML template inline for the view.
  3. TemplateUrl – This is used for defining a URL to an external file containing a template for the view.
  4. Styles – This is used for defining inline CSS to be applied to the template of this component.
  5. StyleUrls – This is used for defining URLs to external style sheets to be applied to the templates of this component.
  6. viewProviders – This is used for defining a list of providers available for this component and its view children

For all configurations, click here.

Let’s understand the component and its parts with the help of below screenshot and component code.

Angular

This shows where the decorators are actually applied to a class and how they are actually responsible for making a class an Angular component.

App.component.ts

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

Nested Components

Now, we will look how to create a nested component (parent component and child component) in Angular 2 applications and how parent and child components will communicate with each other.

I am using the same student project which I have been using in my previous articles so far. You can download it from here.  We will create search bar component and search functionality to the existing student list component.

Let’s understand it with the following steps –

Since we want to make search-bar component as a shared component, we will keep related files in a new folder i.e. shared/searchbar.

Step 1. Add the search bar component TypeScript file

Add a new folder named “Shared” inside app folder and create another folder “SearchBar” inside this “Shared” folder to add the component files. And now, create a TypeScript file “searchbar.component.ts” under this “SearchBar” folder.

Angular

Add the below code into the “searchbar.component.ts” file.

searchbar.component.ts

  1. import { Component, Output, EventEmitter } from '@angular/core'  
  2.   
  3. @Component({  
  4.     selector: 'search-bar',  
  5.     templateUrl: 'searchbar.component.html',  
  6.     moduleId: module.id  
  7. })  
  8. export class SearchBarComponent {  
  9.     @Output()  
  10.     Search = new EventEmitter<string>();  
  11.   
  12.     OnStudentSearch(searchTerm:string): void {  
  13.         this.Search.emit(searchTerm);  
  14.     }  
  15. }  

In the above code, we imported two components, Output and EventEmitter, from Angular core module. With the help of these two, we will inform the parent component when OnStudentSearch method will be called. We created a custom event “Search” which will emit when OnStudentSearch method will be called, so parent component will know about the event. The emit function has been used to fire this custom event.

We have mentioned the search bar template URL in templateUrl property, which we will create in a little bit.

Step 2. Add the search bar template file

Add an html searchbar.component.html file inside the same app -> Shared -> “SearchBar” folder and add the below code into this file,

  1. <div class="form-group">  
  2.     <div class="md-col-4">  
  3.         <label>Enter Student Name:</label>  
  4.     </div>  
  5.     <div class="md-col-4">  
  6.         <input class="form-control" #searchInput type="text" />  
  7.     </div>  
  8. </div>  
  9. <button type="submit" class="btn btn-default" (click)="OnStudentSearch(searchInput.value)">  
  10.     Search  
  11. </button>  

Now our searchbar component is complete to nest inside the existing StudentList component.

Step 3. Nest the SearchBar component inside the StudentList component

Open the existing student.component.html file from app -> student folder and added the below code as highlighted,

  1. <search-bar (Search)="OnStudentSearch($event)"></search-bar>  
  2. <table class="table table-responsive table-bordered table-striped">  
  3.     <thead>  
  4.         <tr>  
  5.             <th>Student ID</th>  
  6.             <th>Name</th>  
  7.             <th>Gender</th>  
  8.             <th>Age</th>  
  9.             <th>Course</th>   
  10.             <th>DOB</th>     
  11.             <th>Grade</th>   
  12.             <th>Rating</th>           
  13.         </tr>  
  14.     </thead>  
  15.     <tbody>  
  16.         <tr *ngFor="let s of students;">  
  17.             <td>{{s.studentID}}</td>  
  18.             <td>{{s.studentName | uppercase}}</td>  
  19.             <td>{{s.gender | lowercase}}</td>  
  20.             <td>{{s.age}}</td>  
  21.             <td>{{s.course | courseCategory}}</td>  
  22.             <td>{{s.DOB | date:'yMMMMd' | uppercase }}</td>  
  23.             <td>{{s.grade | percent:'.2'}}</td>  
  24.             <td>{{s.rating | number:'2.1-2'}}</td>  
  25.         </tr>  
  26.     </tbody>  
  27. </table>  

In the above code, you can see how it has been nested with the StudentList component. This is how we can create nested component in Angular 2.

Step 4. Update StudentList component for search functionality

To filter the student list, we will update the LoadStudents method which will provide us the result after filtering the students with the help of search term passed from child component i.e. SearchBar component. Take a look at the code highlighted below.

  1. import { Component, OnInit} from '@angular/core'  
  2.   
  3. @Component({  
  4.     selector: 'list-student',  
  5.     templateUrl: 'app/student/student.component.html'  
  6. })  
  7. export class StudentListComponent implements OnInit {  
  8.   
  9.     students: any[];  
  10.   
  11.     public LoadStudents(filterText: string): void {  
  12.         this.students = [  
  13.             { studentID: 1, studentName: 'Steve', gender: 'Male', age: 35, course: 'MCA', DOB: '10/12/1982', grade:0.7500,rating:7.5123 },  
  14.             { studentID: 2, studentName: 'Bobby', gender: 'Male', age: 32, course: 'MBA', DOB: '12/1/1985', grade: 0.7850, rating: 7.8223 },  
  15.             { studentID: 3, studentName: 'Rina', gender: 'Female', age: 45, course: 'B.Tech', DOB: '9/11/1972', grade: 0.8525, rating: 8.5263 },  
  16.             { studentID: 4, studentName: 'Alex', gender: 'Female', age: 24, course: 'M.Tech', DOB: '1/1/1993', grade: 0.5540, rating: 5.5123 },  
  17.             { studentID: 5, studentName: 'Rahul', gender: 'Male', age: 26, course: 'MCA', DOB: '1/21/1991', grade: 0.9550, rating: 9.5534 },  
  18.         ];  
  19.   
  20.         if (filterText != "") {  
  21.             var filterStudentList: any[] = [];  
  22.             this.students.forEach(stu => {  
  23.                 if (stu.studentName.toLowerCase().includes(filterText)) {  
  24.                     filterStudentList.push(stu);  
  25.                 }  
  26.             })  
  27.             this.students = filterStudentList;  
  28.         }  
  29.     }  
  30.   
  31.     ngOnInit() {  
  32.         this.LoadStudents("");  
  33.     }  
  34.   
  35.     OnStudentSearch(searchTerm: string): void {  
  36.         this.LoadStudents(searchTerm);  
  37.     }  
  38. }  

Step 5. Register the SearchBar component in Angular app module

Now, we will include our SearchBar component in the Angular app module. Add the code as highlighted below.

  1. import { NgModule }      from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { StudentListComponent } from './student/student.component'  
  6. import { courseCategoryPipe } from './student/student.coursepipe'  
  7. import { SearchBarComponent } from './Shared/SearchBar/searchbar.component'  
  8.   
  9. @NgModule({  
  10.     imports: [BrowserModule],  
  11.     declarations: [AppComponent, StudentListComponent, courseCategoryPipe, SearchBarComponent],  
  12.   bootstrap:    [ AppComponent ]  
  13. })  
  14. export class AppModule { }  

Step 6. Now, run the application to get the expected result

Run the application using F5 or Ctrl + F5 and see the search bar as expected in the browser.

Output

Angular

Let’s take a look at search functionality. Let’s enter the term “Rahul” in the search box and hit the "Search" button to get the student list.

Output on filter

Angular

Summary

In this article, we covered the following topics.

  • What is a component in Angular 2 and what are the main parts of Angular 2 component.
  • What are decorators and what are the types of a decorator in Angular2.
  • What are the configuration properties of a decorator in Angular 2.
  • What is a nested component in Angular 2 and how parent and child components communicate with each other.

To read more articles on Angular 2, please check out the below links,

Write to me in the comment box in case you need any help or you have any questions or concerns. Have a good day!


Similar Articles