如何为Angular Material Tab绑定数据?切换Tab默认选中首个下拉选项
解决方案
一、给mat-tab附加数据并在TS中读取的方法
当然可以给mat-tab附加自定义数据,有两种简单实现方式:
1. 利用HTML自定义属性绑定
在mat-tab标签上通过[attr.data-*]绑定需要传递的数据,比如:
<mat-tab *ngFor="let investorScheme of investorDashboardData?.investorSchemes; let i = index" label="{{investorScheme.schemeName}}" [attr.data-scheme-index]="i" [attr.data-scheme-id]="investorScheme.id"> <!-- 标签页内容 --> </mat-tab>
然后在selectedTabChange事件中读取这些数据:
onTabChange(event: MatTabChangeEvent) { const tabElement = event.tab._elementRef.nativeElement; const schemeIndex = tabElement.getAttribute('data-scheme-index'); const schemeId = tabElement.getAttribute('data-scheme-id'); // 根据获取到的数据处理逻辑 }
2. 通过索引关联数据源
因为mat-tab是通过*ngFor循环investorSchemes生成的,选中标签的索引和数组索引完全对应,直接通过event.index就能拿到对应的investorScheme:
onTabChange(event: MatTabChangeEvent) { const currentScheme = this.investorDashboardData?.investorSchemes[event.index]; if (currentScheme) { // 处理当前选中的scheme数据 } }
二、切换标签页时默认选中第一个mat-option
你当前的核心问题是所有标签页共用了同一个selectedDate变量,导致切换时状态混乱,推荐两种解决思路:
1. 为每个标签页维护独立的选中状态
定义一个对象存储每个方案对应的选中日期,替代单个变量:
// TS文件中 selectedDates: { [schemeId: string]: string } = {}; // 初始化时给每个方案设置默认选中第一个日期 ngOnInit() { this.investorDashboardData?.investorSchemes.forEach(scheme => { if (scheme.displayDates?.length) { this.selectedDates[scheme.id] = scheme.displayDates[0]; } }); }
然后在模板中绑定对应变量:
<mat-select [(ngModel)]="selectedDates[investorScheme.id]"> <mat-option *ngFor="let d of investorScheme.displayDates" [value]="d"> {{d}} </mat-option> </mat-select>
这种方式最可靠,每个标签页的选中状态完全独立,切换时自动显示对应方案的默认值。
2. 利用tab切换事件更新选中值
如果不想修改变量结构,可以在selectedTabChange事件中直接更新selectedDate为当前方案的第一个日期:
<mat-tab-group dynamicHeight="" (selectedTabChange)="onTabChange($event)"> <!-- 标签页内容 --> </mat-tab-group>
onTabChange(event: MatTabChangeEvent) { const currentScheme = this.investorDashboardData?.investorSchemes[event.index]; if (currentScheme?.displayDates?.length) { this.selectedDate = currentScheme.displayDates[0]; } }
同时,首次加载时要给初始选中的标签页设置默认值:
ngOnInit() { const firstScheme = this.investorDashboardData?.investorSchemes[0]; if (firstScheme?.displayDates?.length) { this.selectedDate = firstScheme.displayDates[0]; } }
内容的提问来源于stack exchange,提问作者Pawan Nogariya
相关产品推荐
相关产品推荐

