我想防止用户在MAT-TAB组中导航到其他选项卡。我在这里找到了一个猴子修补程序,如何有条件地阻止用户在MAT-TAB组中导航到其他选项卡。但是我想使用MAT-TAB组API实现此目标。我可以使用FocusChange Event或Event.preventDefault或任何其他方式实现此目标。
这是示例https://stackblitz.com/edit/angular-mat-tab-focuschange-tphyvw
可以通过使用 @Output() selectedIndexChange: EventEmitter<number>
捕获选项卡更改尝试并使用 @Input() selectedIndex: number | null
设置活动选项卡(并设置为当前选项卡索引,如果您不希望新索引来选择新索引(,可以很容易地实现。/p>
<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;
}
}
这是一个工作的演示
如果要有条件阻止用户移动到特定选项卡,则可以根据此条件禁用选项卡。让用户单击选项卡,然后以某种方式试图防止它,似乎对我来说不是一个很好的解决方案。
假设您想用索引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>
理想情况下,您将定义标签的接口,添加属性(例如disabled
(,并基于该属性设置选项卡的disabled
状态。这使您可以轻松启用/禁用一个选项卡。