Search code examples
angularangular-materialmat-tab

Angular mat-tab go back to first tab from another class


I am using mat-tab-group to create two tabs which then link to other components:

            <mat-tab-group>
                <mat-tab label="Notifications">
                    <app-notification-rules-container>
                    </app-notification-rules-container>
                </mat-tab>
                <mat-tab label="Create New">
                     <app-notification-account>
                     </app-notification-account>
                </mat-tab>
            </mat-tab-group>

On the app-notification-account component I have a cancel button and when that is clicked I want to go back to the first tab. How do I navigate back to the first tab from a different component class?

enter image description here


Solution

  • use @Output in your child component. it helps when you want to transfer data from child component to parent. so let say in app-notification you are handling a cross button, so when this button is clicked, emit an event, which will be listened to by the parent (where mat-tab-group) is used, and in mat-tab-group, you can use the selectedIndex property to change the selected tab.

    https://angular.io/guide/inputs-outputs

    So in-app-notification-account.ts

    ...
     constructor() {
       @Output() changeTab = new EventEmitter<();
       // this will emit event , which will be listened by parent
       handleCancel(){
        this.changeTab.emit(true)
      }
    }
    

    in your parent component, where the mat tab is being used in .html

    <mat-tab-group [selectedIndex]="selectedIndex">
    <mat-tab label="Notifications">
                        <app-notification-account (changeTab)="changeTab()">
                        </app-notification-account>
                    </mat-tab>
        </mat-tab-group>
    
    in .component.ts 
    .. changeTab() {
       this.selectedIndex = this.selectedIndex === 1 ?0:1
      // or if you always want to go to first tab just set selectedIndex = 0
    }