Search code examples
angulartypescriptevent-binding

How can I refresh my table content from the child component in the parent component with click event?


I have created a table in the child component and also stored a refresh function in it. Now I would like to call this in my parent component and execute it by clicking on the button. Can you please tell me how I can realize this?

My Code:

// Child-Component

ngOnInit() {
this.refresh();
}

  /**
   * Refresh Data Table
   */
  public refresh() {
    if (!this.isLoading) {
      this.all = false;
      this.clearRows();
      this.loadData();
    }
  }

  public clearRows() {
    const formArray = this.salesAreaForm.get('rows') as FormArray;
    formArray.clear();
  }

// Parent-Component

<button>Refresh Child-Component</button>
<app-child-component></app-child-component>

Solution

  • You should use ViewChild in the parent component.

    import { ..., ViewChild } from '@angular/core';
    
    @ViewChild(ChildComponent) childComponent: ChildComponent;
    
    ...
    childComponent.refresh();
    ...