Angular – Calling a parent component function from child component (EventEmitter)

Published - Updated

Angular Framework

Introduction

In this post you will learn how to call a method on a parent component from a child component using Angular TypeScript. The example below use the @Component decorator and use inline templates rather than imported html file templates.

To be able to call a parents component form the child component, you need to use the 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. This is similar to the @Input() decorator, but here we use the @Output() decorator. Below is an example of how to use EventEmitters.

Parent Component

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

export class ParentComponent {
     myParentFunction(){
          alert(“This has been triggered by the child component!”);          
     }
}

 

Child Component

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

export class ChildComponent extends ParentComponent {
     @Output() refresh: EventEmitter<string> = new EventEmitter();
     childFunction(){
          this.refresh.emit();
     }
}

Here the child component contains a button, which when clicked calls a method called childFunction. This function then calls the refresh emitter, which then calls the parent component method myParentFunction.

Conclusion

Following the above and implementing something similar into your code, you have now successfully used a child component to trigger an action on its parent component.