0
0
Angularframework~30 mins

Child to parent communication flow in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Child to Parent Communication Flow in Angular
📖 Scenario: You are building a simple Angular app where a child component sends a message to its parent component. This is like a child telling a parent something important.
🎯 Goal: Create a child component that sends a message to its parent component using Angular's event system. The parent component will display the message it receives.
📋 What You'll Learn
Create a child component with a button that sends a message when clicked
Create a parent component that listens to the child's message event
Use Angular's @Output and EventEmitter for communication
Display the received message in the parent component's template
💡 Why This Matters
🌍 Real World
This pattern is common in Angular apps where child components need to notify parents about user actions or data changes, like a form input or button click.
💼 Career
Understanding child to parent communication is essential for building interactive Angular applications and collaborating with other developers on component design.
Progress0 / 4 steps
1
Create the child component with a message
Create a child component class named ChildComponent with a string property message set to 'Hello from Child'.
Angular
Need a hint?

Use export class ChildComponent and add a property message with the exact string.

2
Add an EventEmitter to the child component
In ChildComponent, import EventEmitter and Output from @angular/core. Create an @Output() property named messageEvent as a new EventEmitter<string>().
Angular
Need a hint?

Remember to import EventEmitter and Output. Then create @Output() messageEvent = new EventEmitter<string>().

3
Emit the message on button click in child template
Add a button in the ChildComponent template that calls a method sendMessage() when clicked. Implement sendMessage() to emit message using messageEvent.emit(this.message).
Angular
Need a hint?

Add a button with (click)="sendMessage()" and define sendMessage() to emit the message.

4
Receive and display the message in the parent component
Create a parent component class named ParentComponent with a string property receivedMessage initialized to an empty string. In its template, include the app-child selector and bind to (messageEvent) with a method receiveMessage($event). Implement receiveMessage(message: string) to set receivedMessage. Display receivedMessage in the parent template inside a <p> tag.
Angular
Need a hint?

Use <app-child (messageEvent)="receiveMessage($event)"></app-child> in the template and define receiveMessage to update receivedMessage.