The purpose of @Output in Angular: Explained #angular #shorts #interviewprep

Posted by

The @Output decorator in Angular is a way to create custom events that can be emitted and handled by parent components. It allows a child component to communicate with its parent component by emitting custom events.

To use the @Output decorator, you need to define a property in the child component and annotate it with the @Output decorator. This property will serve as the event emitter. When this property is triggered, it will emit an event that the parent component can listen to and handle.

Here’s an example of how to use the @Output decorator in Angular:

“`html

import { Component, Output, EventEmitter } from ‘@angular/core’;

@Component({
selector: ‘app-child’,
template: ``
})
export class ChildComponent {
@Output() customEvent = new EventEmitter();

emitEvent() {
this.customEvent.emit(‘Custom event triggered’);
}
}
“`

In this example, we have a ChildComponent with a button that triggers the emitEvent() method when clicked. Inside the emitEvent() method, we call this.customEvent.emit() to emit a custom event with the message ‘Custom event triggered’.

To handle this custom event in the parent component, you can use the (customEvent) syntax in the parent component’s template:

“`html

“`

“`typescript
// parent.component.ts
import { Component } from ‘@angular/core’;

@Component({
selector: ‘app-parent’,
template: “
})
export class ParentComponent {
handleCustomEvent(message: string) {
console.log(‘Received custom event:’, message);
}
}
“`

In this example, we have a ParentComponent that listens to the customEvent emitted by the ChildComponent. When the custom event is triggered, the handleCustomEvent() method in the ParentComponent is called with the event payload.

Overall, the @Output decorator in Angular is a useful tool for creating custom events and enabling communication between components. It’s commonly used in scenarios where a child component needs to notify its parent component about certain actions or changes. This makes it a very powerful feature when building complex Angular applications.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ermahesh2009
6 months ago

good one can we use subject also?