Angular - @Input() Directive

As we know that component is the basic building block of Angular applications, that means that an Angular application is a collection of components and it is possible that one component contains another component for the purpose of reusability. The component which contains another component is called a parent/container component and the component which is contained/present inside another component is called a child/nested component. Then:

  • How these components communicate with each other?
  • How do we send data from parent component to child component?
  • How do we send data from child to parent component?

So, in this article, we will learn how to send data from parent component to the child component. We will build the below screen and will send the data from parent to child component using @Input(). Please note that I have used bootstrap classes to add some basic style.

To build the below screen, we need two components,

  1. student-list.component.ts (Container/Parent component) - This component is responsible for displaying the student list.

  2. student-count.component.ts(Nested/Child component) - This component is responsible for displaying the 3 Radio buttons named: All, Male, Female, and we are calling this component inside student-list.component.html using the component’s selector directive.
Angular

Now, let’s open student-list.component.ts file and paste the below code.

  1. import {  
  2.     Component  
  3. } from '@angular/core'  
  4. import {  
  5.     FormGroup,  
  6.     FormControl  
  7. } from '@angular/forms'  
  8. @Component({  
  9.     selector: 'my-app',  
  10.     templateUrl: './app/student-list.component.html',  
  11. })  
  12. // This is parent(container) component which contains child(nested) Component(student-count.component.ts)  
  13. export class StudentListComponent {  
  14.     public students: any; // this variable holds the list of students  
  15.     constructor() {  
  16.         //Initialized student array to hold some student object  
  17.         this.students = [{  
  18.             Id: 1,  
  19.             Name: "Mahesh",  
  20.             Address: "Thane",  
  21.             Gender: "Male"  
  22.         }, {  
  23.             Id: 2,  
  24.             Name: "Nishikant",  
  25.             Address: "Chembur",  
  26.             Gender: "Male"  
  27.         }, {  
  28.             Id: 3,  
  29.             Name: "Sameer",  
  30.             Address: "Mulund",  
  31.             Gender: "Male"  
  32.         }, {  
  33.             Id: 4,  
  34.             Name: "Nitin",  
  35.             Address: "Nahur",  
  36.             Gender: "Male"  
  37.         }, {  
  38.             Id: 4,  
  39.             Name: "Siri",  
  40.             Address: "Worli",  
  41.             Gender: "Female"  
  42.         }];  
  43.     }  
  44.     //Below for simplicity I have created 3 method to get the count of students based on the gender  
  45.     //We can do that in single method by passing the parameter.  
  46.     //we will use these functions to pass data to the input properties in child component  
  47.     getTotalStudentsCount() {  
  48.         return this.students.length;  
  49.     }  
  50.     //Get the maleStudentsCount  
  51.     getMaleStudentsCount() {  
  52.         return this.students.filter(student => student.Gender == 'Male').length;  
  53.     }  
  54.     //Get the femaleStudentsCount  
  55.     getFemaleStudentsCount() {  
  56.         return this.students.filter(student => student.Gender == 'Female').length;  
  57.     }  
  58. }  

In the above code, I have just created and initialized the "students" array in the constructor and added three methods which will return us the count of the students based on the gender and we are going to use these methods to give values to input properties using property binding.

Now, open student-list.component.html to add some HTML code.

  1. <body>  
  2.     <!--Here we are using selector as directive to call (render) the child component(student-count.component.ts)-->  
  3.     <!--Now using the property binding in selector tag we are passing data to input properties  
  4.   
  5.         present in child component(student-count.component.ts)  
  6.         ex.[totalStudentsCount]="getTotalStudentsCount()"  
  7.   
  8.     -->  
  9.     <student-count [totalStudentsCount]="getTotalStudentsCount()" -- [maleStudentsCount]="getMaleStudentsCount()" [femaleStudentsCount]="getFemaleStudentsCount()"> </student-count>  
  10.     <hr>  
  11.     <div class="container">  
  12.         <table class="table table-sm">  
  13.             <thead>  
  14.                 <tr>  
  15.                     <th scope="col">Id</th>  
  16.                     <th scope="col">Name</th>  
  17.                     <th scope="col">Address</th>  
  18.                     <th scope="col">Gender</th>  
  19.                 </tr>  
  20.             </thead>  
  21.             <tbody>  
  22.                 <!--using *ngFor directive to iterate over student list-->  
  23.                 <tr *ngFor="let student of students">  
  24.                     <th scope="row">{{student.Id}}</th>  
  25.                     <td>{{student.Name}}</td>  
  26.                     <td>{{student.Address}}</td>  
  27.                     <td>{{student.Gender}}</td>  
  28.                 </tr>  
  29.             </tbody>  
  30.         </table>  
  31.     </div>  
  32. </body>  

In the above HTML code, I have used child component, i.e., student-count component selector as a directive to render inside the student-list component and I am passing the values to the input properties of child component using property binding.

  1. <student-count [totalStudentsCount]="getTotalStudentsCount()" --[totalStudentCount] is the input property in student-count.component and I am assigning values by calling respective method which is present in .ts file [maleStudentsCount]="getMaleStudentsCount()" [femaleStudentsCount]="getFemaleStudentsCount()">   
  2. </student-count>  

And then, I am rendering the table using the *ngFor directive.

Now, open the student-count.component.ts file and paste the following code.

  1. import {  
  2.     Component,  
  3.     Input  
  4. } from "@angular/core";  
  5. @Component({  
  6.     selector: 'student-count',  
  7.     templateUrl: './app/student-count.component.html'  
  8. })  
  9. export class StudentCountComponent {  
  10.     //here we have decorated variables using @Input directive means that these  
  11.     //variables will get data from parent component  
  12.     //in our case,  
  13.     //it is from student-list.component  
  14.     @Input()  
  15.     totalStudentsCount: any;  
  16.     @Input()  
  17.     maleStudentsCount: any;  
  18.     @Input()  
  19.     femaleStudentsCount: any;  
  20.     //this variable is use to select the All Radio button by default  
  21.     selectedRadioButton: any = "All";  

Here, I have declared 3 variables and decorated those variable with @Input() directives which means these variables will get values from the parent component.

See the comments in the above code for more information.

Now, open the student-count.component.html file and paste the following code.

  1. <div class="container">  
  2.     <p style="font-weight: bold;">Select:</p>  
  3.     <form> <label class="radio-inline">  
  4.   
  5.             <input type="radio" name="optradio" value="All" [(ngModel)]="selectedRadioButton">All({{totalStudentsCount}})  
  6.   
  7.         </label> <label class="radio-inline">  
  8.   
  9.             <input type="radio" name="optradio" value="Male" [(ngModel)]="selectedRadioButton">Male({{maleStudentsCount}})  
  10.   
  11.         </label> <label class="radio-inline">  
  12.   
  13.             <input type="radio" name="optradio" value="Female" [(ngModel)]="selectedRadioButton">Female({{femaleStudentsCount}})  
  14.   
  15.         </label> </form>  
  16. </div>  

In the above code, I’m rendering 3 radio buttons using HTML and displaying the respected count of students based on gender using interpolation ( {{ //TODO }} ).

HTML output screenshot
Angular

In the above image, we are getting the count of respective students using input directive. In this way, we can pass the data from parent component to a child component.

In our next article, we will learn how to pass data from child component to the parent component using @Output() directive and how to raise the custom event.

Hope this will help you.

Thanks!

You can download the complete code from my GitHub repository using below link.

https://github.com/mahesh353/InputDirective


Similar Articles