Sunday, 29 December 2024

Angular Inputs and Outputs: Sharing Data Between Parent and Child Components

A common pattern in Angular is sharing data between a parent component and one or more child components. 

Implement this pattern with the @Input() and @Output() decorators.

Consider the following hierarchy: 

<parent-component>
  <child-component></child-component>
</parent-component>

@Input() and @Output()

give a child component a way to communicate with its parent component. 

@Input()   lets a parent component update data in the child component. Conversely, @Output() lets the child send data to a parent component.


Sending data to a child component
The @Input() decorator in a child component or directive 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'; // First, import Input
export class ItemComponent {
  @Input() item = ''; // decorate the property with @Input()
}

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

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

item.component.html

<p>
  Today's item: {{item}}
</p>








No comments:

Post a Comment