Search code examples
angularangular-material-5

How to reset/refresh tab body data in Angular Material if user move from one tab to another tab?


Here is my sample code

Main Controller

<mat-tab-group id="report">
<mat-tab label="Poll">
<div class="demo-tab-content">
  <app-poll></app-poll>
</div>

</mat-tab>
<mat-tab label="Survey">
<div class="demo-tab-content">
  <app-survey></app-survey>
</div>
</mat-tab>

In each tab, there is different controller named - Poll and Survey. Here I want to refresh\reset one tab data if the user moves from one to another.

Any simple way to achieve that?


Solution

  • If you don't want to use @Input parameters, you can also use @ViewChild to get a reference to your child components and then call a method on these components to refresh the data

    component.ts

      import {ViewChild} from '@angular/core';
      import { MatTabChangeEvent } from '@angular/material';
      //...
      @ViewChild(PollComponent) private pollComponent: PollComponent;
      @ViewChild(SurveyComponent) private surveyComponent: SurveyComponent;
    
    
      //...
      onTabChanged(event: MatTabChangeEvent) 
      {
        if(event.index == 0)
        {
            this.pollComponent.refresh();//Or whatever name the method is called
        }
        else
        {
            this.surveyComponent.refresh(); //Or whatever name the method is called
        }
      }
    

    component.html

    <mat-tab-group id="report" (selectedTabChange)="onTabChanged($event)">
    
    </mat-tab>