Prashant Pimpale
Prashant Pimpale

Reputation: 10697

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?

Upvotes: 11

Views: 34122

Answers (3)

Dattu Gaade
Dattu Gaade

Reputation: 41

In angular material 8, there is an option for lazy loading the component in tabs when user selects it.

you can simply wrap your component to be lazy loaded in ng-template as shown in link below

https://material.angular.io/components/tabs/overview#lazy-loading

Upvotes: 4

David
David

Reputation: 34435

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>

Upvotes: 14

ForestG
ForestG

Reputation: 18085

You can read about component interaction types here.

You need something like this:

1. Children -> parent

In both of the components, have an need an emitter.

MainController:

  <app-poll (changed)=this.update($event)></app-poll>

  <app-survey (changed)=this.update($event)></app-survey>

In the components, have an event emitter defined:

@Output() changeEmitter = new EventEmitter<any>();

when you want to trigger the reset, write something like this:

changedEmitter.emit(<<you can insert objects here>>);

This will trigger the call in their parent's this.update().

in that method, you can define other logic to trigger a reset, but from parent-child, the easiest way is to bind a data object, which you can change:

2. Parent-> children

  <app-survey (changed)=this.update(newValue) [data]="surveyData"></app-survey>

in the main comp ts:

private surveyData: any;

update(newValue: any){
  surveyData =  <<something>>
}

in the survey comp:

@Input() private data: any;

Upvotes: 1

Related Questions