Call method of parent component in child component Angular 8

Dung Do Tien Nov 18 2020 651

I have two components in Angular 8:

Parent component

@Component({
  selector: 'parent-component',
  template: '<div> <child-component></child-component> <div>',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  reloadData() {
    alert("reloaded");
  }
}

Child component

import { Component } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `<h2>Child component</h2>`
})
export class ChildComponent {
  callMethod() {
    // Call method of parent component here.
  }
}

Now I want to call reloadData() method of parent component inside callMethod() method of the child component.

Please support me if you know any solution.

Have 1 answer(s) found.
  • S

    Sandeep Kumar Nov 18 2020

    To call a method of parent component in an anywhere in child component you can use  @Output() and EventEmitter of angular to handle. Let see an example:

    Parent component

    @Component({
      selector: 'parent-component',
      template: '<div> <child-component (startReLoadData)="reloadData()"></child-component> <div>',
      styleUrls: ['./app.component.css']
    }) 

    In that :

    (startReLoadData): This is a custom event, you can replace it with any name.

    reloadData(): Method of parent component that wants to be called in the child component.

    Child component

    First, we need to declare a variable, this variable has to map with the custom event of the parent component.

    @Output()
    startReLoadData: EventEmitter<any> = new EventEmitter<any>(); 

    Secondary, we can call the method of the parent component anywhere you want:

    this.startDoingFilter.emit(); 
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close