Custom event Binding: @Output Decorator | send data from child component to parent component |Data Binding | Angular 15+
How to pass data from child component to parent using custom data binding and output decorator.
To pass data from a child component to a parent component in Angular, you can use the @Output decorator and the EventEmitter class. Here's how you can do it:
1: In the child component's TypeScript file, define an @Output property and create an instance of the EventEmitter class:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="onButtonClick(1)">Button 1</button>
<button (click)="onButtonClick(2)">Button 2</button>
<button (click)="onButtonClick(3)">Button 3</button>
`
})
export class ChildComponent {
@Output() buttonClicked = new EventEmitter<number>();
onButtonClick(id: number) {
this.buttonClicked.emit(id);
}
}
In this example, we have defined an @Output property named buttonClicked that emits an event of type number. We are also defining a method onButtonClick() that takes an id parameter and emits the buttonClicked event with the id value.
2: In the parent component's HTML template, add the child component and bind to the buttonClicked event:
<app-child (buttonClicked)="onButtonClicked_p($event)"></app-child>
In this example, we are adding the app-child component to the parent component's template and binding to its buttonClicked event. The $event parameter represents the value emitted by the buttonClicked event. $event is not changeable
3: In the parent component's TypeScript file, define a method to handle the buttonClicked event:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<h2>Parent Component</h2>
<app-child (buttonClicked)="onButtonClicked_p($event)"></app-child>
`
})
export class ParentComponent {
onButtonClicked_p(id: number) {
console.log(`Button ${id} clicked`);
}
}
In this example, we have defined a method onButtonClicked() that takes an id parameter and logs a message to the console.
Now, when a button is clicked in the child component, the buttonClicked event will be emitted with the id value, and the onButtonClicked() method in the parent component will be called with the id value as its parameter.