angularangular-materialtabs

Is there a way attach data or ngModel with material tab?


I have a mat-tab-group like this, where the tab content is decided based on the selected tab:

<mat-tab-group dynamicHeight="">
    <mat-tab *ngFor="let investorScheme of investorDashboardData?.investorSchemes"
        label='{{investorScheme.schemeName}}'>
        <mat-form-field class="w-50" appearance="outline">
            <mat-label>As On Date</mat-label>
            <mat-select [(ngModel)]="selectedDate">
                <mat-option *ngFor="let d of investorScheme.displayDates" [value]="d">
                    {{d}}
                </mat-option>
            </mat-select>
        </mat-form-field>
        <table>
        </table>
    </mat-tab>
</mat-tab-group>

As you can see I am showing a select box inside a tab which options are set dynamically based on the selected tab.

My requirement is to select the very first mat-option by default whenever a tab is changed.

I was finding a way to somehow attach or pass data with selected tab which I can read in (selectedTabChange) event, but even after searching a lot I could not find any way to do so.

Is there any way to attach some data to the tab that can be read in the ts file?

If not, is there a way to set the first option of the select default selected when the tab changes and the select is loaded based on the tab?


Solution

  • Yes, you can work with the selectedTabChange event to trigger the function:

    tabChange(event: MatTabChangeEvent) {
      this.selectedDate =
        this.investorDashboardData.investorSchemes[event.index].displayDates[0];
    }
    
    <mat-tab-group dynamicHeight="" (selectedTabChange)="tabChange($event)">
      ...
    </mat-tab-group>
    

    Definitely, your tabChange function can add more arguments to pass the data if required.

    Demo @ StackBlitz