Welcome Guest! (App Version 3.1)

websitnero logo name

@Input

@Input for Component Communication

@Input decorator is used when we want to get data from parent component. This means that data will be sent from some parent component and it will be catched by the help of '@Input' decorator in the child component.

In parent component - app.component.ts

age = 25;

In parent Component - app.component.html

<app-home [ageValue] = {{age}}><app-home>

In Child Component - home.component.ts

@Input() ageValue;

In Child Component - home.component.html

<p> {{ageValue}}</p>

Practical Example of @Input

Please follow the mentioned steps:

  1. Create a compennt 'home' which we will use as parent
  2. Create a component 'hearts' that we will use as child

  1. You'll get the following folder structure - with 'home' and 'hearts' inside components folder and all inside 'src' folder.

  1. Now, pass the value from the parent 'home component' as property binding - to - the child component (hearts component) and then gather the value of the variable via @Input() decorator. Then, show the value on the 'view' of 'hearts component' from the value gathered in 'logic' (.ts) of the hearts component.

app.component.ts

<app-home></app-home>

home.html

<div>
  <app-hearts [heartsCount]="noOfHearts"></app-hearts>
</div>

home.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

  noOfHearts: Number = 50;

  constructor() { }

  ngOnInit() {
  }

}

hearts.component.html

<div>
 The total number of hearts is: {{heartsCount}}
</div>

hearts.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-hearts',
  templateUrl: './hearts.component.html',
  styleUrls: ['./hearts.component.css']
})

export class HeartsComponent implements OnInit {

  @Input() heartsCount;

  constructor() { }

  ngOnInit() {
  }

}
  1. You'll get the following result.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.