Sharing data between Angular Component

An Angular component is the basic build block of an Angular framework. The component is responsible for managing a template and providing it with the data and logic it needs. Components can contain other components. This is known as composition. Components can communicate with each other in a loosely coupled manner and in this article we will learn Sharing data between Angular Component. There are various ways Angular’s components can share data, including the following:

What is Property Binding and an example

Components can accept data being passed to them using the component inputs/property binding, which makes it possible for a parent component to bind data directly into a child component, which is a way to pass data down the component tree. The square bracket [] is used to represent property binding.

Demo on property binding

We will use two examples first to used property binding in the component own template and second bind data from parent to child property.
Sharing data between Angular Component
Angular 9 input binding example

In our first bindings example we have linked the value of the name property in our component to the value of the input field in the view.

The binding is dynamic, so, as the value of the input field changes so as property name value is also changed. The value of the input field will be
synchronized to the same value and we do not have to write any code to do that.

Example 2 on property binding to sending data from parent to child component

Data flow downwards from the parent component to child components. When you create a child component that receives data from a parent, we must explicitly tell Angular to expect that data as input, using the @Input decorator. We place the @Input decorator next to the instance variable to which the data will be injected from outside. We will learn this by creating a project and pass data from the app root component to child component hotel components.


Step 1: Create project $ng new InputDataBinding
Step 2: Create new component hotel $ng generate component hotel
Step 3: Edit app component
We will add a hotels array object containing a list of the hotel name and its location. The [hotelData] is outside the property of the current component and is the name of a property in a child component. We had to assign [hotelData] a value of each iteration of hotels array object of the parent component.

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

@Component({
  selector: 'app-root',
  template:`
  <app-hotel *ngFor="let hotel of hotels" [hotelData]="hotel"></app-hotel>` ,
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  hotels = [
    { name: 'Taj Palace', location: 'Delhi'},
    { name: 'Leela Place', location: 'New York'},
    { name: 'Park Hyatt ', location: 'Sydney'}
    ];
}

Step 4: Data sharing from parent to child component
By default, all properties of the component are only accessible inside the components and not from outside of its component. To bind child properties to parent component we need to explicit about which properties you want to expose to the parent. You place the @Input decorator next to the instance variable to which the data will be injected from outside. When you pass data into a component from the outside, you pass that data into the component using input properties. To use input() decorator we need parent/child relationships among components.

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

@Component({
  selector: 'app-hotel',
  template: `
  <div>
    <strong> {{ hotel.name }} </strong>
    <em>: {{ hotel.location }}</em>
  </div>
`,
  styleUrls: ['./hotel.component.scss']
})
export class HotelComponent implements OnInit {
  // tslint:disable-next-line: no-input-rename
  @Input('hotelData') hotel: { name: string, location: string };
  constructor() { }

  ngOnInit(): void { }

}

 When you tag a component’s member variable with @Input(), you are telling Angular that the value for that variable should come from the same-name property of the associated template tag of its in the parent component.

In @Input() decorator we don’t need to provide an argument if the name of the property of child component is same as corresponds to the name of the attribute in a parent component. Sometimes we may want the name of the input property to be different from the name of the instance variable to which it will be injected. That’s when we need to use an alias name instead of property own name, which allows you to specify the input property name. The alias may be specified inside parentheses in the @Input decorator and in our case we use hotelData as an alias name.

Safe Navigation Operator (?.) is an Angular template binding operator, is not available in javascript and is not the same as ? the ternary operator. When we are retrieving remote data in our case hotel data using HTTP requests and data may not available at the time when we are passing data using @Input() properties. As a result, we pass null data to the child component and when the child component attempt to display data containing the null object. Which can cause Angular to throw exceptions and not display the data when it has come back from the server. We can easily solve this by using a safe navigation operator (?.) as an example {{ hotel?.name }}

More information on component interaction in an angular check official documentation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top