Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Prashant Pimpale Avatar asked Apr 03 '18 12:04

Prashant Pimpale


People also ask

How do you conditionally prevent users from navigating to other tab in Mat tab group?

The solution 🕶 First, we need to add a click listener on the mat-tab-group and disable all tabs because if tabs are not disabled then the user will be able to navigate on them and we want to navigate on tabs conditionally not manually.

How do you refresh a component from another component in angular 8?

Clicking on the Reload Page button,will execute the constructor() and ngOnInit() of the AppComponent,ChildComponent and TestComponent again. 3. Clicking on the Reload Test Component button, we will navigate to the /test route and execute the constructor() and ngOnInit() of the TestComponent again.

What is matTabContent?

Material tabs (with matTabContent ) are rendering multiple instances of the tab body inside the same tab when switching away and back too fast.

What is Mat tab in angular?

Tabs and navigation While <mat-tab-group> is used to switch between views within a single route, <nav mat-tab-nav-bar> provides a tab-like UI for navigating between routes.


1 Answers

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>
like image 138
David Avatar answered Nov 01 '22 13:11

David