Angular Tutorial: Child to Parent Communication 🎯

beginner
20 min

Angular Tutorial: Child to Parent Communication 🎯

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. 📝

Understanding the Parent-Child Relationship 📝

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.

Creating Our Sample Components 📝

Let's start by creating two components: ParentComponent (our parent) and ChildComponent (our child).

bash
ng generate component ParentComponent ng generate component ChildComponent

Setting Up the Parent Component 📝

In the ParentComponent HTML file, we'll create a place for our child component and an empty property to receive data from the child.

html
<!-- 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!'; }

Setting Up the Child Component 📝

Now, let's update our ChildComponent to send data to its parent.

html
<!-- 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!'); } }

Binding the Child to Parent 📝

Finally, let's update our ParentComponent to bind to the child's @Output event.

html
<!-- 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! 🎉

Quick Quiz
Question 1 of 1

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! 💡