Reputation: 10697
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
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
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
Reputation: 18085
You can read about component interaction types here.
You need something like this:
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:
<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