Let's Develop An Angular Application - Transfer The Data From Parent Component To Child Component Using @input() Decorator

This is the 5th article published as part of my 'Let's develop an Angular application' article series.
 
Please read my first two articles to get an idea about what we are trying to accomplish in this series of articles.
 
 To read my previous article, please click here >> #4 - Create Model for our Bike entity
 
In this article , we are going to do the following tasks:
  • Transfer each array item in the ‘bikeEl’ variable into to the child component 'bike-list-box' from app component
  • Display the details of each bike object in bike-list-box component
Here, we are going to get familiar with @Input() decorator.
 
@Input decorator will marks a class field as an input property.
 
The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property's value.
 
Ref : https://angular.io/api/core/Input
 
@Input() decorator can be used pass the data from parent component to child.
 
For this first we need to create variable inside bike-list-box.component file.
 
Then convert the variable into input property by using the @Input() decorator.
  1. @Input() bike:Bike;    
Please refer the screenshot below. 
 
 
Then, edit the ‘bike-list-box.component.html’  to display the bike details.
 
We can use the string interpolation {{}} feature to display the data from class variable to template file.
 
Please refer to    the below html statements to display the bike details. 
  1. <div>    
  2.     <h4>Bike Name : {{bike.name}}</h4>    
  3.     <h5>Company:{{bike.company}}</h5>    
  4.     <p>Price:{{bike.price}}</p>    
  5.     <p>Top Speed :{{bike.topspeed}} Kmph</p>    
  6.     <hr>       
  7. </div>   
Now, our bike-list-box component is ready to accept input from its parent and display the details in the input.
 
Next step is to pass the data from parent component to child component.
 
Open the app.component.html file again.
 
We can use the property binding to pass the array element into the bike-list-box component. 
  1. [bike]="bikeEl"   
Please refer to the screenshot to get a clear picture.
 
 
Save all changes and go to the browser to see the result.
 
If everything is correct, we will see the screen as below.
 
 

Conclusion

 
In this article, we have used the @Input() decorator to transfer the data from parent component to the child component.
 
Here, we have replicated the bike-list-box component multiple times using a ngFor statement. 
 
In the next article, we will install Bootstrap and will use the basic bootstrap style classes to improve the UI.
 
To read my next article, please click here >> #6 - Bootstrap installation and Usage
 
 
Happy Learning ! 


Similar Articles