Data between parent and child components can be managed using @Input and @Output decorators.
1. Using @Input()
This allows a parent component to bind data to a child component.
Parent Component Template:
<app-child [childData]="parentData"></app-child>
Child Component Class:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `...`
})
export class ChildComponent {
@Input() childData: any;
}
In this example, parentData from the parent component is passed to childData in the ChildComponent.
2. Using @Output()
This allows a child component to send data to a parent component through event emitters.
Child Component Class:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendDataToParent()">Send Data</button>
`
})
export class ChildComponent {
@Output() dataEmitter = new EventEmitter<any>();
sendDataToParent() {
const data = { message: 'Hello Parent!' };
this.dataEmitter.emit(data);
}
}
Parent Component Template:
<app-child (dataEmitter)="receiveData($event)"></app-child>
Parent Component Class:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `...`
})
export class ParentComponent {
receiveData(data: any) {
console.log('Data from child received:', data);
}
}
In this setup, when the button in the child component is clicked, it emits data to the parent component, which can then handle it via the receiveData function.