Welcome to our comprehensive guide on Angular! Today, we're diving into an essential aspect of Angular: child-to-parent communication. This guide is designed to be both beginner-friendly and packed with practical examples to help you grasp the concept effectively. 📝
In Angular, components can be nested like a tree structure. The top-most component is the root or parent, and the other components are its children. Communication between these components is crucial. Today, we focus on how children can communicate with their parent.
Let's start by creating two components: ParentComponent (our parent) and ChildComponent (our child).
ng generate component ParentComponent
ng generate component ChildComponentIn the ParentComponent HTML file, we'll create a place for our child component and an empty property to receive data from the child.
<!-- parent.component.html -->
<child [data]="parentData"></child>
<!-- ts file -->
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentData = 'Hello from Parent!';
}Now, let's update our ChildComponent to send data to its parent.
<!-- child.component.html -->
<p>Hello from Child!</p>
<button (click)="sendDataToParent()">Send Data</button>
<!-- ts file -->
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Output() dataChange = new EventEmitter<string>();
sendDataToParent() {
this.dataChange.emit('Hello from Child!');
}
}Finally, let's update our ParentComponent to bind to the child's @Output event.
<!-- parent.component.html -->
<child (dataChange)="handleDataChange($event)"></child>
<!-- ts file -->
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentData = 'Hello from Parent!';
handleDataChange(newData: string) {
this.parentData = newData;
}
}Now, when you click the "Send Data" button in the child component, the parent component's data will be updated! 🎉
What does the `@Output` decorator do in Angular?
That's it for today! You've learned how to establish communication between child and parent components in Angular. In the next lessons, we'll dive deeper into Angular's features and best practices. Keep coding! 💡