Nested component in angular 2



Introduction

In the previous article of the series Learning Angular 2 step by step, we learned about Angular 2 Component. Now in this tutorial, we will learn a little more about angular 2 component where we will see how to create a nested component and how the components (parent component & child component) communication with each other.

Before reading this article, I would recommend reading my previous tutorial where I have explained about Angular 2 component.  

Today in this tutorial, we will continue learning Angular 2 step by step and here we will learn all about Angular 2 component for better understanding.

In the previous tutorial, we have created a component EmployeeList Component for showing list of employee data. Now in this tutorial, we will create an another component SearchBar Component and then we will see  how to nest the SearchBar component inside the EmployeeList component and
communicate with each other.

Open the previous application we have created in the previous part of the series in VS code editor.

Create the SearchBar component.

In the below image you can see, how the search bar will look like. We will make the SearchBar component reusable and for making it reusable we have to make the component dynamic means the SearchBar component input placeholder text should be received from its parent component and after clicking the search button the parent component should know about the event. Let's see how we can do that.



Let's create the SearchBar Component.
Here in our application, We will make the SearchBar Component reusable and the Component will be used from multiple components. So I will create a folder named Shared first inside the src > App folder then I will add an another folder inside the Shared folder and then we will add a typescript file searchbar.component.ts for creating the SearchBar component.

Right click on the folder App inside the src folder  > New Folder > enter folder name Shared and now right-click on the Shared folder > New Folder > enter name SearchBar and then right click on the SearchBar folder > New File > enter file name searchbar.component.ts 

Here is our searchbar.component.ts file.

import { Component } from "@angular/core";
@Component({
    moduleId:module.id,
    selector:'search-bar',
    templateUrl:'search-bar.component.html'
})
export class SearchBarComponent{
    public PlaceHolderText:string = "Search...";

    OnSearch(searchText){
       
    }
}

You can see here in line 8, I have added a property PlaceHolderText which will be the placeholder text of the input box of SearchBox component. But as we have discussed, this should be coming from its parent component. We can do that with the help of @Input decorator. Also, we have to inform the parent component when OnSearch method will be called and this we can do with the help of  @Output and EventEmitter.

@Input decorator of Angular 2 is used for passing data into a component. And we will use @Output and EventEmitter to pass data out and bind to an event So the parent will know about the event.
Let's do it. I am going to update our component code.

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
    moduleId:module.id,
    selector:'search-bar',
    templateUrl:'search-bar.component.html'
})
export class SearchBarComponent{
    @Input()
    public PlaceHolderText:string = "Search...";

    @Output()
    Search = new EventEmitter<string>();

    OnSearch(searchText){
        this.Search.emit(searchText);
    }
}

Here you can see in line 1, I have imported Input, Output & EventEmitter. And in line 9, I have added the @Input decorator in the property PlaceHolderText. It allows passing data from parent to the child component.

See in line 11, where I have added the @output decorator on the newly added Search property of type EventEmitter. That's mean we have created a custom event of name Search.

EventEmitter is used for emitting custom events in components what I have done in line 15, we have fired our custom created Search event.

Add the template file search-bar.component.html

Now we will add the search-bar.component.html file in the src > App > Shared > SearchBar folder.

<nav class="navbar navbar-default">
    <div class="navbar-header">
        <a class="navbar-brand" href="#">Search</a>
    </div>
    <div class="navbar-form navbar-left">
        <div class="form-group">
            <input class="form-control" #searchInput type="text"
              [placeholder]="PlaceHolderText"
              (keyup.enter)="OnSearch(searchInput.value)">
        </div>
        <button type="submit" class="btn btn-default"
           (click)="OnSearch(searchInput.value)">
            Search
        </button>
    </div>
</nav>

Nest the SearchBar Component inside the EmployeeList Component

Open the file employee-list.component.html from src > App > EmployeeList folder and update with the below HTML code.

<h2>Employee List</h2>
<search-bar [PlaceHolderText]="'Search employee...'"
    (Search)="OnEmployeeSearch($event)"></search-bar>
<table class="table table-responsive table-bordered table-striped">
    <thead>
     <tr>
         <th>Employee ID</th>
         <th>Employee Name</th>
         <th>Contact No</th>
         <th>Designation</th>
     </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of EmployeeList">
            <td>{{item.EmployeeID}}</td>
            <td>{{item.FirstName}} {{item.LastName}}</td>
            <td>{{item.ContactNo}}</td>
            <td>{{item.Designation}}</td>
        </tr>
    </tbody>
</table>
You can see here in the yellow marked lines that we placed an HTML tag called inside the EmployeeList component template, this is how we can nest components in Angular 2.

Update EmployeeList component for filter the employee list

We will update the LoadInitialData method for filter the employee list with the search text value that we will get from SearchBar component.
import {Component, OnInit} from '@angular/core'
import {EmployeeModel} from '../Models/EmployeeModel'
@Component({
    selector:'employee-list',
    templateUrl:'employee-list.component.html',
    moduleId: module.id
})
export class EmployeeListComponent implements OnInit{
    public EmployeeList: Array<EmployeeModel> = [];
    public LoadIntialData(filterText:string):void{
        this.EmployeeList = [{
            EmployeeID:1,
            FirstName: "Sourav",
            LastName:"Mondal",
            ContactNo: "1234567890",
            Designation:"Software Developer"
        },
        {
            EmployeeID:2,
            FirstName: "Rik",
            LastName:"Decosta",
            ContactNo: "1478523690",
            Designation:"Software Developer"
        },{
            EmployeeID:3,
            FirstName: "Jhon",
            LastName:"Decosta",
            ContactNo: "5874213690",
            Designation:"Software Developer"
        }];

        if(filterText !=""){
            var afterFilterEmpList: Array<EmployeeModel> = [];
            this.EmployeeList.forEach(item=>{
                if(item.FirstName.toLowerCase().includes(filterText) ||
                item.LastName.toLowerCase().includes(filterText))
                {
                    afterFilterEmpList.push(item);
                }
            })

            this.EmployeeList = afterFilterEmpList;
        }


    }

    ngOnInit(){
        this.LoadIntialData("");
    }
    OnEmployeeSearch(searchText):void{
            this.LoadIntialData(searchText);
    }
}

Update app.module.ts file

We have done creating SearchBar component and also updating EmployeeList component. Now we have to add the SearchBar component in the NgModule declarations meta-data in app.module.ts file before running the application.
import { NgModule } from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {AppComponent} from "./app.component"
import {EmployeeListComponent} from './EmployeeList/employee-list.component'
import {SearchbarComponent} from './Shared/SearchBar/searchbar.component'


@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent,EmployeeListComponent, SearchbarComponent],
    // bootstrap:[AppComponent],
    bootstrap:[EmployeeListComponent]
})
export class AppModule{

}

Run the application

For run the application go to View menu > click on Integrated Command > it will open the terminal > write npm start in the terminal and hit the enter key.

Live Demo Download

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.