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?
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.
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.
Material tabs (with matTabContent ) are rendering multiple instances of the tab body inside the same tab when switching away and back too fast.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With