@Output() and EventEmitter are used to pass events/data from a child component up to a parent component.
typescript
// child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendData()">Send to Parent</button>
`
})
export class ChildComponent {
@Output() dataEvent = new EventEmitter<string>();
sendData() {
this.dataEvent.emit('Hello from Child!');
}
}
// parent.component.ts
@Component({
selector: 'app-parent',
template: `
<app-child (dataEvent)="receiveData($event)"></app-child>
<p>{{ message }}</p>
`
})
export class ParentComponent {
message = '';
receiveData(data: string) {
this.message = data;
}
}You should see
(Clicking the button in the child component makes 'Hello from Child!' appear in the parent component)