Angular 2 Container and Nested Components

Angular 2 Container and Nested Components

In this article, I am going to discuss the Angular 2 Container and Nested Components with an example. As part of this article, we will discuss the following two things with an example.

  1. What is a nested component?
  2. What is a container component?

In our few upcoming articles, we will discuss the following things

  1. How to pass data from the nested component to container component?
  2. How to pass data from the container component to the nested component?
  3. What are component input and output properties?
  4. How to create custom events using Event Emitter class?
  5. What are ng-container directive and its use?

We are going to use the following example to understand all the above concepts.

Angular 2 Container and Nested Components

As shown in the above image, we have a table that displays a list of students.  You can also see that above the table we have 3 radio buttons i.e. All, Male and Female and next to each radio button we also display the count of students as shown below.

Angular 2 Container and Nested Components

All(5) radio button has the total count of students i.e. both male and female students. Male(3) radio button has the total count of male students and similarly, the Female(2) radio button has the total count of female students.  

At the moment the All(5) radio button is selected, so all the students (both male and female) are displayed in the table. But, if I select the Male(3) radio button, then only the 3 male students should be displayed in the table. Similarly, if I select the Female(2) radio button then only the female students should be displayed in the table.

What are the Angular 2 Container and Nested Components?

To achieve the above example, we need to create two components. One component will display the list of students in a table while the other component will display the radio buttons and the count of students.

To display the list of students, we can make use of the StudentListComponent that we already created in our previous article.

Here in this article, we will create a component with the name StudentCountComponet to display the radio buttons along with their total count of students.

Once we create the StudentCountComponet then we will nest this StudentCountComponet within the StudentListComponet and when we do so, then the StudentCountComponet becomes the nested component or the child component and StudentListComponet becomes the container component or parent component as shown in the image below.

Angular 2 Container and Nested Components

In our previous article, we already have implemented the code for StudentListComponent which is as shown below.

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

@Component({
    selector: 'student-list',
    templateUrl: 'app/Student/StudentList.Component.html',
    styleUrls: ['app/Student/StudentList.Component.css']
})

export class StudentListComponent {
    students: any[] = [
        {
            ID: 'std101', FirstName: 'Pranaya', LastName: 'Rout',
            DOB: '12/8/1988', Gender: 'Male', CourseFee: 1234.56
        },
        {
            ID: 'std102', FirstName: 'Anurag', LastName: 'Mohanty',
            DOB: '10/14/1989', Gender: 'Male', CourseFee: 6666.00
        },
        {
            ID: 'std103', FirstName: 'Priyanka', LastName: 'Dewangan',
            DOB: '7/24/1992', Gender: 'Female', CourseFee: 6543.15
        },
        {
            ID: 'std104', FirstName: 'Hina', LastName: 'Sharma',
            DOB: '8/19/1990', Gender: 'Female', CourseFee: 9000.50
        },
        {
            ID: 'std105', FirstName: 'Sambit', LastName: 'Satapathy',
            DOB: '4/12/1991', Gender: 'Male', CourseFee: 9876.54
        }
    ];
}

Following is the StudentList.Component.css file code that we also created in our previous article

table {
    color: #369;
    font-family: Arial, Helvetica, sans-serif;
    font-size: large;
    border-collapse: collapse;
}

td {
    border: 1px solid #369;
    padding:5px;
}

th{
    border: 1px solid #369;
    padding:5px;
}

Now let’s create the StudentCountComponent and to do so, add a new TypeScript file to the Student folder with the name it StudentCount.Component.ts and then copy and paste the following code in it.

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

@Component({
    selector: 'student-count',
    templateUrl: 'app/Student/StudentCount.Component.html',
    styleUrls: ['app/Student/StudentCount.component.css']
})
export class StudentCountComponent {
    all: number = 5;
    male: number = 3;
    female: number = 2;
}

Here, we have set the selector=’student-count’. So, we can use this selector as a directive where we want to use this component. We are going to next this StudentCountComponent within the StudentListComponent using the ‘student-count selector as a directive.

Within the StudentCountComponent, we declare 3 properties (all, male and Female) and at the moment we have hardcoded the values for these properties. In our next article, we will discuss how to pass the values to these properties from the container component i.e. from the StudnetListComponent.

Once you create the StudentCountComponent, then you need to register it in the module.ts file. To do so, modify the app.module.ts file as shown below.

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { StudentListComponent } from './Student/StudentList.component';
import { StudentTitlePipe } from './Student/studentTitle.pipe';
import { StudentCountComponent } from './Student/StudentCount.Component';

@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent, StudentListComponent, StudentTitlePipe, StudentCountComponent],
    bootstrap: [AppComponent]
})
export class AppModule { } 

Add a new Style Sheet within the Student folder and Name it StudentCount.Component.css and then copy and paste the following style class. 

StudentCount.Component.css

.radioClass {
    color: #369;
    font-family: Arial, Helvetica, sans-serif;
    font-size: large;
}

Now let’s add a view template for StudentCountComponent and to do so, add a new HTML page within the Student folder and name it as StudentCount.Component.html and then copy and paste the following HTML in it.

StudentCount.Component.html
<span class="radioClass">Show : </span>

<input type="radio" name="options" />
<span class="radioClass">{{"All(" + all + ")"}}</span>

<input name="options" type="radio">
<span class="radioClass">{{"Male(" + male + ")"}}</span>

<input name="options" type="radio">
<span class="radioClass">{{"Female(" + female + ")"}}</span>

Notice that in the above HTML, we have 3 radio buttons and bound them to the 3 properties (all, male, female) that we have in the component (StudentCountComponent) class. Here, we are using the interpolation technique for data-binding. 

Now, we need to nest the StudentCountComponent in StudentListComponent component and to do so, we need to use the StudentCountComponent selector (i.e. student-count) as a directive <student-count></student-count> on StudentListComponent component. So modify the StudentList.Component.html file as shown below

StudentList.Component.html
<student-count></student-count>
<br/><br/>
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Gender</th>
            <th>DOB</th>
            <th>Course Fee</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let student of students'>
            <td>{{student.ID | uppercase}}</td>
            <td>{{student.FirstName | studentTitle:student.Gender}}</td>
            <td>{{student.Gender}}</td>      
            <td>{{student.DOB | date:'dd/MM/y'}}</td>
            <td>{{student.CourseFee | currency:'USD':true:'1.2-2'}}</td>
        </tr>
        <tr *ngIf="!students || students.length==0">
            <td colspan="10">
                No Students to display
            </td>
        </tr>
    </tbody>
</table>

That’s it. We have done with the first phase of our implementation. At this point, if you run the application and then you should see the student count radio buttons and the student list. 

In the above example, we have hardcoded the student counts within the StudentCountComponent. In the next article, we will discuss how to pass the student count values from the container component i.e. from the StudentListComponent to the nested component i.e. StudentCountComponent.  

SUMMARY:

In this article, I try to explain the Angular 2 Container and Nested Components with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *