DEV Community

Pragnesh Makwana
Pragnesh Makwana

Posted on

How to call a parent component method from child component using EventEmitter

What is an EventEmitter?
To call a parent component method from a child component, you need to use an Angular EventEmitter. Emitting events allows your components to communicate with one another when a certain action has been executed, in this example the action is on click.

To emit an event, we need to use the @Output decorator on the child component and register a handler for the event by subscribing to the instance on the parent component.

Child Component

In your ChildComponent, extend the ParentComponent class. This allows the child to Emitt events to the parent.

Use the @Output() decorator with the name of your event, in this case, I have called the event “alert”. When the button in the template is clicked, the CreateAlert() method is called. This method then Emitts the event “alert”, which the parent will be subscribed to.

@Component({
  selector: "child-component",
  template: "I’m a child component <button (click)='makeAlert()'>Click Me</button>"
})

export class ChildComponent extends ParentComponent {
    @Output() alert: EventEmitter<string> = new EventEmitter();
    makeAlert(){
         this.alert.emit();
    }
}
Enter fullscreen mode Exit fullscreen mode

Parent Component

In your parent components template, where the child compone is included, add a handler that is named the same as the event which is being emitted. In this case, we should be listening to the “alert” event. When the event is emitted by the child, the showAlert() method is called.

@Component({
   selector: 'parent-component',
   template: "
    <p>I’m a parent component</p>
    <child-component (alert)=”showAlert()”></child-component>"
})

export class ParentComponent {
     showAlert(){
          alert(“This has been triggered by the child component!”);  
   }
 }
Enter fullscreen mode Exit fullscreen mode

Discussion (0)