I have tried to make this concept as simple as possible. I hope anyone not clear with @Input and @Output decorators of Angular will understand after going through this blog.
Basic usage of @Input and @Output Decorators -
- @Input - To pass data from Parent to Child Component
- @Output - To pass data from Child to Parent Component
I have created 2 Components - TestParentComponent and TestChildComponent.
Task
I will add 2 numbers in the Parent component and pass that total value to the Child component. Later, using that value, I will perform the multiplication of text.
Input the value in Child Component and pass that updated value to the Parent Component.
Let's understand @Input to pass the data from Parent to Child Component by adding 2 numbers in Parent.
After generating, the component will be something like below.
Task
I will add 2 numbers in the Parent component and pass that total value to the Child component. Later, using that value, I will perform the multiplication of text.
Input the value in Child Component and pass that updated value to the Parent Component.
Let's understand @Input to pass the data from Parent to Child Component by adding 2 numbers in Parent.
After generating, the component will be something like below.
- import {
- Component,
- OnInit
- } from '@angular/core';
- @Component({
- selector: 'app-test-parent',
- templateUrl: './test-parent.component.html',
- styleUrls: ['./test-parent.component.css']
- })
- export class TestParentComponent implements OnInit {}
Now, first we will add two textboxes in test-parent.component.html file so that we can get the input values and perform the addition operation.
- <p> Parent Component </p>
- <div class="form-group">
- <input type="text" class="form-control" placeholder="Number1" (input)="getTotalAmt()" [(ngModel)]="num1" name="num1" id="num1" />
- </div>
- <div class="form-group">
- <input class="form-control" placeholder="Number2" type="text" (input)="getTotalAmt()" [(ngModel)]="num2" name="num2" id="num2" />
- </div>
As you can see, I have added two text inputs which call the getTotalAmount() method on the input event. Now, I am updating the Parent class to perform the addition.
- export class TestParentComponent implements OnInit {
- num1: string;
- num2: string;
- Total: number;
- constructor() {}
- ngOnInit() {}
- ConvertToInt(val: string): number {
- return parseInt(val);
- }
- getTotalAmt() {
- this.Total = this.ConvertToInt(this.num1) + this.ConvertToInt(this.num2);
- }
- }
You will see the similar output shown below as per your inputs.
Now, we will update the child component's HTML and add to the Parent.
- <p> Child Component </p>
- <div class="form-group">
- <input type="text" class="form-control" placeholder="Number3" />
- </div>
- <app-test-child></app-test-child> <!-- In test-parent.component.html add this code -->



Nitin SawantPosted Sep 5, 2018, 7:21 AM
Very confusing
Hadshana KamalanathanPosted Sep 4, 2018, 7:48 PM
Thanks for sharing...