0
0
Angularframework~30 mins

@Output decorator with EventEmitter in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Output Decorator with EventEmitter in Angular
📖 Scenario: You are building a simple Angular app where a child component sends a message to its parent component when a button is clicked.
🎯 Goal: Create a child component that uses the @Output decorator with EventEmitter to send a message to the parent component. The parent component will listen and display the message.
📋 What You'll Learn
Create a child component with an @Output property named messageEvent that is an EventEmitter<string>.
Add a button in the child component template that triggers a method to emit a message string through messageEvent.
In the parent component template, listen to the messageEvent from the child component and bind it to a method named receiveMessage.
In the parent component class, create a message property to store the received message and display it in the template.
💡 Why This Matters
🌍 Real World
This pattern is common in Angular apps where child components need to communicate user actions or data changes to their parent components, such as form inputs, buttons, or custom controls.
💼 Career
Understanding @Output and EventEmitter is essential for Angular developers to build interactive and modular applications with clear component communication.
Progress0 / 4 steps
1
Create the child component with EventEmitter
In the child component TypeScript file, import Output and EventEmitter from '@angular/core'. Then create an @Output property called messageEvent that is a new EventEmitter<string>().
Angular
Need a hint?

Remember to import Output and EventEmitter from '@angular/core'.

2
Add a button to emit a message
In the child component class, add a method called sendMessage that calls this.messageEvent.emit('Hello from Child'). In the child component template, add a button with a click event that calls sendMessage().
Angular
Need a hint?

The button's click event should call the sendMessage method.

3
Listen to the event in the parent component
In the parent component template, add the child component selector <app-child> and bind its messageEvent to a method called receiveMessage($event).
Angular
Need a hint?

Use the child component selector and bind messageEvent to receiveMessage($event).

4
Add message property and receiveMessage method in parent
In the parent component TypeScript file, create a message property initialized to an empty string. Add a method called receiveMessage that takes a message: string parameter and sets this.message to it.
Angular
Need a hint?

Initialize message as an empty string and update it inside receiveMessage.