How do you send an event from a child component to the parent?
To send an event from a child component to its parent in Angular, you use a combination of @Output() and EventEmitter.
Step by step
- In the child component:
- Create a property with
@Output()of typeEventEmitter. - Call
.emit()on the desired event.
typescript
@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Click me</button>`
})
export class ChildComponent {
@Output() clicked = new EventEmitter<string>();
sendMessage() {
this.clicked.emit('Hello from the child component!');
}
}- In the parent component:
- Subscribe to the event through
(eventName)in the template. - Handle the data received from the child component.
typescript
@Component({
selector: 'app-parent',
template: `<app-child (clicked)="handleClick($event)"></app-child>`
})
export class ParentComponent {
handleClick(message: string) {
console.log(message); // "Hello from the child component!"
}
}Conclusion: the child component uses
EventEmitter.emit(), the parent subscribes through(eventName)and receives the data.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.