默认关闭的mat-expansion-panel点击其他面板时异常触发(closed)事件求助
解决mat-accordion中未打开面板触发closed事件的问题
这个问题其实是Angular Material的mat-accordion默认手风琴行为导致的——当你打开新面板时,组件会自动关闭其他所有面板,哪怕目标面板本来就是关闭状态,这时候它的closed事件还是会被触发。要实现只有当面板被打开过之后再关闭时才执行函数,我们可以通过跟踪面板的打开状态来过滤无效触发。
解决方案步骤
1. 在组件类中添加状态变量
首先在你的组件.ts文件里定义一个变量,用来记录第一个面板是否被真正打开过:
isGeneralPanelExpanded = false;
2. 更新模板中的事件绑定
修改第一个mat-expansion-panel的事件绑定,在opened事件中标记面板为已打开状态,在closed事件中通过状态判断来执行目标函数:
<mat-accordion class="example-headers-align myaccordion"> <mat-expansion-panel hideToggle="true" class="myexpension" (opened)="isGeneralPanelExpanded = true; fetchGeneralInfo()" (closed)="handleGeneralPanelClose()" #generalInfo > <mat-expansion-panel-header> <mat-panel-title> General Information </mat-panel-title> </mat-expansion-panel-header> </mat-expansion-panel> <mat-expansion-panel hideToggle="true" class="myexpension" #guaInfo (opened)="fetchGua()" > <mat-expansion-panel-header> <mat-panel-title> Gurantor Information </mat-panel-title> </mat-expansion-panel-header> </mat-expansion-panel> </mat-accordion>
3. 在组件类中实现处理函数
添加handleGeneralPanelClose函数,只有当面板确实被打开过的时候才执行collpaseClose(0):
handleGeneralPanelClose() { if (this.isGeneralPanelExpanded) { this.collpaseClose(0); this.isGeneralPanelExpanded = false; // 重置状态,等待下一次打开 } }
原理说明
- 初始状态下
isGeneralPanelExpanded为false,对应面板默认关闭的状态。 - 当用户第一次打开第一个面板时,
opened事件触发,把isGeneralPanelExpanded设为true,同时执行fetchGeneralInfo()。 - 之后无论用户是主动关闭第一个面板,还是打开第二个面板导致第一个面板被自动关闭,
closed事件触发时,我们都会先检查isGeneralPanelExpanded是否为true——只有面板确实被打开过,才会执行collpaseClose(0),然后重置状态。 - 如果面板从未被打开过(比如页面加载后直接点第二个面板),
isGeneralPanelExpanded还是false,就不会执行目标函数,完美解决你的问题。
内容的提问来源于stack exchange,提问作者Nishant Varshney
相关产品推荐
相关产品推荐

