Event Binding to Parent Components
Shows how to emit events from a child component using the EventEmitter, allowing parent components to handle changes and enforce one-way data flow.
// ChildComponent.js
import { EventEmitter } from '@angular/core';
export class ChildComponent {
// Creating an instance of EventEmitter
onAction = new EventEmitter();
// Function to emit an event
performAction() {
// ... some code to handle the action ...
// This is where the event with the payload is emitted
this.onAction.emit({ payload: 'some data' });
}
}
This is the child component which includes EventEmitter to emit events. It defines an `onAction` EventEmitter and a `performAction` function that emits the event with a payload when called.
// ParentComponent.js
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `<app-child (onAction)="handleAction($event)"></app-child>`
})
export class ParentComponent {
// Function to handle the event from the child
handleAction(eventData) {
console.log('Event received:', eventData);
// ...code to handle event...
}
}
This is the parent component that uses the child component. It handles events emitted by the child component through the `handleAction` function, which is bound in the component's template to the child's `onAction` event.