Angular 2 – Two Ways to Pass Data to Components

0
This article represents concepts and code samples in relation with how one could pass data from one component to another. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.
As Angular 2 is primarily based on components and components interaction, it is important to understand how data is passed from one component to another. Data is passed between the component using property bindings. Take a look at the syntax below:

<user [value]="user"></user>

In above syntax, user component’s property “value” is bound to “user” property of the parent component. The data type of the bound property needs to be matched. Thus, if the “value” is an object, the “user” property of parent component also needs to be an object. To achieve the contactual requirement, one could take define a user “interface” and then create property of interface type for consistency. Following is sample code for User interface. The code below could be saved in a separate file such as user.ts and the interface could be imported in different component appropriately.

export interface User {
	id: number,
	name: string,
	email: string,
	address: string,
	age: number
}

Following are two different syntax that could be used in the Child component for it to receive the input from the parent component.

  • Usage of @Input decorator: @Input decorator is used to define the property which receives the data from parent property. In other words, the @Input decorator adds metadata to the class that makes the “value” property, in the code below, available for property binding under the “value” alias. Take a look at the User component below and usage of @Input decorator.
    import {Component, View} from 'angular2/core';
    import {User} from './user';
    
    @Component({
      selector: 'user',
    })
    @View({
      template: '{{value.name}}'
    })
    export class UserComponent {
      @Input('value') value: User;
    }
    
  • Usage os inputs array: Another way is to use “inputs” array in the @Component metadata. Take a look at the following code:
    import {Component, View} from 'angular2/core';
    import {User} from './user';
    
    @Component({
      selector: 'user',
      inputs: ['value']
    })
    @View({
      template: '{{value.name}}'
    })
    export class UserComponent {
      value: User;
    }
    

 

Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, .NET, C/C++, mobile programming languages etc and, computing fundamentals such as application security, cloud computing, API, mobile apps, google glass, big data etc.Recently, he has been digging deep into the field of data science and machine learning.

Follow him on Twitter and Google+.
Ajitesh Kumar

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.