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
- When instantiating the Child Component, bind the Child Component property in the Parent Component.
@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; }
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
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>
export class AppComponent { title = 'Component Interaction'; Counter = 5; increment() { this.Counter++; } decrement() { this.Counter--; } }
Various ways to use @Input Decorator
- 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
export class ChildComponent { @Input() count: number; }
@Component({ selector: 'child-component', inputs: ['count'], template: `<h2>Child Component</h2> current count is {{ count }} ` }) export class ChildComponent {}
Aliasing input Property
export class ChildComponent { @Input('MyCount') count: number; }
template: ` <h1>Welcome to {{title}}!</h1> <child-component [MyCount]=ClickCounter></child-component>
Detecting the Input changes
- Using OnChanges LifeCycle Hook
- Using Input Setter
Using OnChanges LifeCycle Hook
How to Use ngOnChanges to Detect Changes
- Import the @angule/core library's OnChanges interface, SimpleChanges, and SimpleChange.
- 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.
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); } } }
Using Input Setter
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; }