Using mat-tab-group focusChange event, How to stop user navigating to other tab

Viewed 2667
2 Answers

it is easily achievable by using @Output() selectedIndexChange: EventEmitter<number> to catch tab change attempts and using @Input() selectedIndex: number | null to set active tab (and set to current tab index if you don't want new index to get selected)

<mat-tab-group #mtg (selectedIndexChange)="selectedIndexChange($event)">
  <mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab">
    Contents for {{tab}} tab
  </mat-tab>
</mat-tab-group>
  @ViewChild("mtg") tg: MatTabGroup;
  tabs = ['First', 'Second', 'Third', "Fourth"];
  current = 0;

  selectedIndexChange(evt: any) {
    if (evt % 2) {
      this.tg.selectedIndex = this.current;
      console.log("You cannot select even numbered tabs, sorry ^_^");
    } else {
      this.current = evt;
    }
  }

here is a working demo

If you want to conditionally prevent the user from moving to a specific tab, you could just disabled the tab based on this condition. Letting the user click the tab and then somehow trying to prevent it, doesn't seem like a good solution to me.

Let's say you wanted to disable the tab with the index 1:

<mat-tab-group (focusChange)="show()" [selectedIndex]="selected.value"
               (selectedIndexChange)="selected.setValue($event)">
  <mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab" [disabled]="index === 1">
    Contents for {{tab}} tab
  </mat-tab>
</mat-tab-group>

Ideally you would define an interface for your tabs, add a property (for example disabled) and based on that property set the disabled state of the tab. This lets you easily enable/disable a tab.

Related