In angular, @Output is used in a child component to emit events to parent component.
This allows communication from the child to the parent component by sending data or triggering methods in the parent.
1. Setup the Child Component
Use @Output and EventEmitter in the child component to emit an event.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from Child!');
}
}
Setup the Parent Component
Listen to the event emitted by the child component and handle it.
Parent Component Template:
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>Message from Child: {{ message }}</p>
Parent Component TypeScript:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
message: string = '';
receiveMessage(event: string) {
this.message = event;
}
}