Search code examples
angulartabsangular-materialmat-tab

How can I focus on an specific mat-tab


<mat-tab-group mat-stretch-tabs #tabGroup (focusChange)="tabChanged($event)" [selectedIndex]="0">
    <mat-tab label="DATOS EXPEDIENTE">
      <div class="example-large-box mat-elevation-z4">
        <app-informe-expediente></app-informe-expediente>
      </div>
    </mat-tab>
    <mat-tab label="DATOS ALTERACIÓN">
      <div class="example-large-box mat-elevation-z4">
        <app-informe-alteracion></app-informe-alteracion>
      </div>
    </mat-tab>
    <mat-tab label="DATOS INMUEBLES">
      <div class="example-large-box mat-elevation-z4">
        <app-informe-inmuebles></app-informe-inmuebles>
      </div>
    </mat-tab>
    <mat-tab label="FLUJO DE TRAMITACIÓN">
      <div class="example-large-box mat-elevation-z4">
        <app-informe-tramitacion></app-informe-tramitacion>
      </div>
    </mat-tab>
    <mat-tab label="DOCUMENTOS ASOCIADOS">
      <div class="example-large-box mat-elevation-z4">
        <app-informe-documentos></app-informe-documentos>
      </div>
    </mat-tab>
</mat-tab-group>      

This is my mat-tab-group that depends on a browser, so it triggers every time I click my submit button. I need to know how can I get the first tab with index 0 to get focused every time I click my submit button.
I know it has to do with index and that stuff but I don't know, I am controlling the indexes with MatTabChangeEvent.


Solution

  • You can use two way binding on selectedIndex to keep track of which tab is selected, and set selectedIndex to 0 on the button click

    Template

    <mat-tab-group [(selectedIndex)]=selectedIndex>
      <mat-tab label="First"> Content 1 </mat-tab>
      <mat-tab label="Second"> Content 2 </mat-tab>
      <mat-tab label="Third"> Content 3 </mat-tab>
    </mat-tab-group>
    
    <button mat-raised-button (click)="selectedIndex = 0">
      Reset tab
    </button>
    

    Component

    @Component({
      selector: 'tab-group-basic-example',
      templateUrl: 'tab-group-basic-example.html'
    })
    export class TabGroupBasicExample {
      selectedIndex = 0;
    }