{{announcement.body}}
{{announcement.title}}

Angular 2: Two Ways to Pass Data

DZone 's Guide to

Angular 2: Two Ways to Pass Data

As Angular 2 is based on components and component interaction, it is important to understand how data is passed from one component to another.

· Web Dev Zone ·
Free Resource

As Angular 2 is based on components and component interaction, it is important to understand how data is passed from one component to another. Data is passed between components using property bindings. Take a look at the syntax below:

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

In the above syntax, the user component’s property, value, is bound to the  user property of the parent component. The data type of the bound property needs to match — if  value is a string,  user also needs to be a string. To achieve this requirement, one could define a user interface and then create a property of that interface type for consistency. The following is sample code for the user interface. The code below could be saved in a separate file such as user.ts and the interface could be imported into different components as needed.

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

The following are two different techniques that could then be used in the Child component for it to receive the input from the parent component:

  • Usage of the @Input decorator: The @Input decorator is used to define the property which receives data from the 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 the usage of the @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 of inputs array: Another way is to use the 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;
    }

Both of these techniques support type conformity in Angular 2.


If you enjoyed this article and want to learn more about Angular, check out our compendium of tutorials and articles from JS to 8.

Topics:
angular 2 ,web dev ,web application data ,typescript ,angular tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}