How To Pass Data From Parent To Child Component

How To Pass Data From Parent To Child Component

In this article, we will learn about how Angular passes data to the child component. The @Input Decorator is used to connect between Angular Components. We also see at how child components use the OnChanges life Cycle hook or a Property Setter to monitor changes to these Input properties.

Passing data to a child component

We established an Angular Application in the previous courses and then added a child component to it. We also looked at how data binding is used by Angular Component to communicate with its View (templates).

If these components can't interact with one another, they're useless. If they are to serve any practical purpose, they must communicate with one another.

How to Pass data to a child component

The Parent Component in Angular can connect with the child component by setting the Property of the child component. To accomplish this, the child component must make its properties available to the parent component. The @Input decorator is used by the Child Component to do this.

In the Component for Children

  • @Angular/Core Library's @Input module should be imported.
  • Using the @Input decorator, mark those properties that require data from the parent as input properties.

In the component's parent

@Input Decorator

The @Input Decorator is used to customize the component's input settings. Change tracking is also supported by this decorator.

When you mark a property as an input property, Angular uses Property Binding to inject values into the component property. The [] brackets are used in the Property Binding. Inside the square brackets is the Binding Target (Property of the child component). Quotes around the Binding source. Property Binding is one method of connecting a Component to a Target in a template.

@Input example

Let's create a basic component to explain how to use @Input.

A counter will be present in our application, which will be incremented by the Parent Component. This counter is then passed to the child component for display in its template by the parent component.

The Child Component with @Input Decorator

Under the src/app folder, create the ChildComponent.ts file. Also, copy the code below.

import { Component, Input  } from '@angular/core';
 
@Component({
    selector: 'child-component',
    template: `<h2>Child Component</h2>
               current count is {{ count }}
    `
})
export class ChildComponent {
    @Input() count: number;
}

Now, let us look at the code in detail
First, we import the Input decorator from @angular/core
import { Component, Input  } from '@angular/core';

The inline template for the child component has been defined, and it displays the current count.
@Component({
    selector: 'child-component',
    template: `<h2>Child Component</h2>
               current count is {{ count }}
   `
})

The Parent Component is expected to provide the count to the Child component. As a result, in ChildComponent, use the @Input decorator to decorate the count property.
export class ChildComponent {
    @Input() count: number;
}

Bind to Child Property in Parent Component

Now it's time to transmit the Count data from the Parent Component to the Child Component.

Open the app.component.ts and add the following code
import { Component} from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
        <h1>Welcome to {{title}}!</h1>
        <button (click)="increment()">Increment</button>
        <button (click)="decrement()">decrement</button>
        <child-component [count]=Counter></child-component>` ,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Component Interaction';
  Counter = 5;
 
  increment() {
    this.Counter++;
  }
  decrement() {
    this.Counter--;
  }
}

The Parent Component's inline template has two buttons. The counter is incremented or decremented by the buttons.
<button (click)="increment()">Increment</button>
<button (click)="decrement()">decrement</button>

The child component is invoked inside the parent component in the following line.
<child-component [count]=Counter></child-component>

Inside the square bracket, we're using the count property, which is a property of the child component. We connect it to the Parent Component's Counter property.

In Angular, the square bracket signifies Property Binding.

Finally, in the Parent component, we will add a counter and set it to 5 as shown below.
export class AppComponent {
  title = 'Component Interaction';
  Counter = 5;
 
  increment() {
    this.Counter++;
  }
  decrement() {
    this.Counter--;
  }
}

Now, run the application and see the display looks like below screen


How To Pass Data From Parent To Child Component


To see if the changes have been propagated to the child component, click the Increment and Decrement buttons. 

Various ways to use @Input Decorator

To make the property in the child component an input property, we use the input @Input Decorator. You may do it in two ways with Angular.
  • To decorate the class property, use the @Input decorator.
  • Using the component decorator's input array meta data

Using the @Input decorator to decorate the class property

This was demonstrated in the preceding case.
export class ChildComponent {
     @Input() count: number;
}

Using the component decorator's input array metadata

The same result may be performed by use the @Component decorator's Input array, as demonstrated below.
@Component({
    selector: 'child-component',
    inputs: ['count'],
    template: `<h2>Child Component</h2>
    current count is {{ count }}
`
})
export class ChildComponent {}

The count property has been moved to the inputs array of the component metadata.

Aliasing input Property

As shown below, you can alias the input property and use the aliased name for the parent component.
export class ChildComponent {
     @Input('MyCount') count: number;
}

We're using the MyCount alias to alias the count property.

We can use the MyCount in the parent component, as seen below.
template: `
   <h1>Welcome to {{title}}!</h1>
   <child-component [MyCount]=ClickCounter></child-component>

Detecting the Input changes

We looked at how to use the @Input decorator and property binding to transmit data from the parent to the child.

It's not enough to just pass the data to the child component; it also has to know when the input changes so it can react.

In Angular, there are two techniques to detect when input changes in the child component.
  1. Using OnChanges LifeCycle Hook
  2. Using Input Setter

Using OnChanges LifeCycle Hook

ngOnChanges is a lifecycle hook that angular triggers when a data-bound input property changes. A SimpeChanges object is passed to this method, which contains the current and prior property values. Using this hook, we may intercept input property changes in the child component.

How to Use ngOnChanges to Detect Changes

  1. Import the @angule/core library's OnChanges interface, SimpleChanges, and SimpleChange.
  2. Use the ngOnChanges() function to implement the ngOnChanges() method. The SimpleChanges object, which contains the changes in each input property, is passed to the method.

Let's add some changes to our Child Component so that it may use the OnChanges hook.

Add the following modifications to the child.component.ts file.
import { Component, Input, OnChanges, SimpleChanges, SimpleChange  } from '@angular/core';
 
@Component({
    selector: 'child-component',
    template: `<h2>Child Component</h2>
               current count is {{ count }}
    `
})
export class ChildComponent implements OnChanges {
    @Input() count: number;
 
    ngOnChanges(changes: SimpleChanges) {
 
        for (let property in changes) {
            if (property === 'count') {
              console.log('Previous:', changes[property].previousValue);
              console.log('Current:', changes[property].currentValue);
              console.log('firstChange:', changes[property].firstChange);
            } 
        }
    }
}

First, we'll import the necessary libraries.
import { Component, Input, OnChanges, SimpleChanges, SimpleChange  } from '@angular/core';

After that, make changes to the class to implement the OnChanges interface.
export class ChildComponent implements OnChanges {

}

ngOnChanges method
ngOnChanges(changes: SimpleChanges) {

      for (let property in changes) {
          if (property === 'count') {
            console.log('Previous:', changes[property].previousValue);
            console.log('Current:', changes[property].currentValue);
            console.log('firstChange:', changes[property].firstChange);
          } 
      }
  }

As a SimpleChange object, this method gets all modifications made to the input properties. The SimpleChange object has property names as keys and SimpleChange instances as values.

SimpleChange is a class that allows you to make changes to your Represents a fundamental change from one value to another. There are three people in the class.

previousValue:any :- Previous value of the input property.
currentValue:any :- New or current value of the input property.
FirstChange():boolean :- Boolean value, which tells us whether it was the first time the change has taken place

To get our property count, we loop through the SimpleChanges.

As you click on the increment and decrement buttons in the parent component, run the application and view the console log to watch the logs.

Using Input Setter

As demonstrated below, we can use the property getter and setter to detect changes to the input property.

Create a private property called _count in the Child Component.
private _count = 0;

Create a getter and setter for the property count, and use the @Input Decorator to decorate it. The setter function's input modifications are intercepted and logged to the console.
@Input()
set count(count: number) {
    this._count = count;
    console.log(count);
}
get count(): number { return this._count; }

Conclusion

In this article, We learned how to transmit data from a parent component to a child component in this tutorial. The @Input Decorator is used by the Child Component to decorate the property. We use property pinding in the Parent Component to link it to the Parent Component's Property or method. We can also use the ngOnChanges life cycle hook to track changes made to the Input Property. Alternatively, you can use the Property setter.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post