"I Know That Now: Keep Learning"

Sponsored by: Ubora PLC

Angular 2/4/5 – Calling a parent component function from child component (EventEmitter)

Posted by Dillon | 14th January 2018

To be able to call a parents component form the child component, you need to use Angular EventEmitter.  Emitting events allows your components to communicate with one another when a certain action has been executed. This is similar to the @Input() decorator, but here we use the @Output() decorator. Below is an example of how to use EventEmitters.

This post is intended for those who already have an understanding of Angular.

Parent Component 

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

export class ParentComponent {
     myFunction(){
          alert(“This has been called from the child component!”);          
     }
}

 

Child Component 

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

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

Here the child component contains a button, which when clicked calls a function name clickFunction. This function then calls the refresh emitter, which then calls the parent component function myFunction.

If you have any questions, please leave a comment.

For more Development tutorials, check out our Web Development category.

Related Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *