7. Parent-child communication with @Input()

A common pattern in Angular is sharing data between a parent component and one or more child components. To implement this pattern use the @Input() decorator.

Consider the following hierarchy:

<parent-component>

  <child-component></child-component>

</parent-component>

The <parent-component> serves as the context for the <child-component>.

@Input() lets a parent component update data in the child component. 

Parent to child component communication using @Input decorator

The @Input() decorator in a child component signifies that the property can receive its value from its parent component.

To use @Input(), you must configure the parent and child.

Configuring the child component:

To use the @Input() decorator in a child component class, first import Input and then decorate the property with @Input(), as in the following example.

import { Component, Input } from ‘@angular/core’;

export class ChildComponent{

  @Input() childData:string = ”;

}

In this case, @Input() decorates the property childData, which has a type of string, however, @Input() properties can have any type, such as number, string, boolean, or object. The value for childData comes from the parent component.

Next, in the child component template, add the following:

<p>{{childData}}</p>

Configuring the parent component:

The next step is to bind the property in the parent component’s template. In this example, the parent component template is parent.component.html.

  1. In the parent component class, designate a value for parentData:
  2. Use the child’s selector, here <app-child>, as a directive within the parent component template.

Placing the child component in the parent component

  1. Use property binding to bind the childData property in the child to the parentData property of the parent.

<app-child [childData]=”parentData”></app-child>

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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