如何在获得用户确认前阻止Angular Material的MatTab标签页切换?
解决方法
问题根源
你当前绑定的click事件触发时,Angular Material 内置的标签页切换逻辑已经执行完成,因此会出现先切换标签再弹出确认框的问题。
改造步骤
1. 修改组件模板
取消click事件绑定,改为单向绑定selectedIndex控制激活标签,同时监听selectedIndexChange事件拦截切换操作:
<mat-tab-group [selectedIndex]="currentTabIndex" (selectedIndexChange)="onTabChange($event)"> <mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab"> <app-spread></app-spread> </mat-tab> </mat-tab-group>
2. 修改组件TS逻辑
新增变量存储当前激活标签索引,在拦截事件中处理确认逻辑,用户确认后再修改激活索引完成切换:
// 新增变量,存储当前激活的标签索引,默认值根据你的初始选中标签调整 currentTabIndex = 0; // 替换原来的tabClick方法 onTabChange(targetIndex: number) { // 自定义判断逻辑:需要弹出确认框的场景 const targetTabLabel = this.tabs[targetIndex]; if (targetTabLabel !== 'First') { this.confirm(targetIndex); return; } // 无需确认直接切换 this.currentTabIndex = targetIndex; } // 调整confirm方法,接收目标标签索引 public confirm(targetIndex: number) { const dialogRef = this.dialog.open(ConfirmationDialogComponent, { maxHeight: '200px', maxWidth: '767px', width: '360px', disableClose: true, data: { title: 'Confirmation Message', content: 'There are valid statements that are not Final. Set the statements as Final?' } }); dialogRef.afterClosed().subscribe(result => { if (result === 1) { // 用户确认,完成标签切换 this.currentTabIndex = targetIndex; } // 用户取消则不做任何操作,标签保持原状态 }); }
实现原理
我们通过单向绑定selectedIndex接管了标签页的切换控制权,只有手动修改currentTabIndex的值才会触发标签切换,因此可以在拦截事件中先弹出确认框,等用户操作完成后再决定是否更新索引完成切换。
内容的提问来源于stack exchange,提问作者MuthuKani K
相关产品推荐
相关产品推荐

