You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目mat-button-toggle绑定click/change事件无法触发问题咨询

问题根因

  1. 事件绑定位置错误
    (change)是mat-button-toggle-group组件的输出事件,不属于单个mat-button-toggle组件,绑定到单个toggle上自然不会触发。
  2. 内部点击事件被拦截
    mat-button-toggle默认会吞噬内部子元素的点击事件,用来处理自身选中状态切换逻辑,你绑定在内部fa-icon上的click事件会被阻止冒泡,无法触发绑定方法。
  3. ngFor渲染异常不是框架bug
    你没有给*ngFor配置trackBy函数,当tableauSeances数组引用发生更新时(哪怕内容完全不变,只要数组整体被重新赋值),ngFor会销毁所有旧DOM节点重新渲染,可能导致事件绑定失效,手动编写的固定节点不会触发重绘逻辑,所以可以正常响应事件。

修正方案

1. 调整HTML绑定逻辑

把change事件绑定到group组件上,给每个toggle添加value属性,同时给ngFor增加trackBy优化渲染,需要单独绑定图标点击的话增加阻止冒泡逻辑:

<div class="container-fluid">
  <div *ngIf="saisonSelectionneeCalendrier && saisonSelectionneeCalendrier.id && verifierOptionActive()" class="row calendriers">
    <mat-button-toggle-group 
      appearance="legacy"
      (change)="clicSurUneSeance($event)"
    >
      <mat-button-toggle 
        *ngFor="let seance of tableauSeances!; trackBy: trackBySeanceId"
        [value]="seance"
      >
        <fa-icon icon="calendar-alt"></fa-icon>
        {{ seance.dateSeance!.format('dddd D MMMM YYYY') }}
        <fa-icon 
          *ngIf="verifierSeanceExistante(seance)" 
          class="check" 
          icon="check-circle"
          (click)="$event.stopPropagation(); onClickSeance(seance)"
        ></fa-icon>
      </mat-button-toggle>
    </mat-button-toggle-group>
  </div>
</div>

2. 补充TS逻辑

增加trackBy函数,调整事件处理逻辑:

// 优化ngFor渲染,避免不必要的节点重绘
trackBySeanceId(index: number, seance: { identifiant: string }): string {
  return seance.identifiant;
}

clicSurUneSeance(event: MatButtonToggleChange): void {
  console.log(event.value);
  // 点击toggle整体的处理逻辑,需要的话可以在这里调用原来的onClickSeance
  // this.onClickSeance(event.value);
}

onClickSeance(seance: any): void {
  // 原有的点击check图标的逻辑
}

内容的提问来源于stack exchange,提问作者Broshet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:18:04