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

Angular中通过ngFor渲染mat-button-toggle时动态设置模板引用变量并在同标签内使用的实现方案

Angular中通过ngFor渲染mat-button-toggle时动态设置模板引用变量并在同标签内使用的实现方案

嘿,我懂你现在的困扰!原来手动写每个mat-button-toggle的时候,靠模板引用变量(比如#yesterday)来判断选中状态并设置ngClass,但换成*ngFor循环生成按钮后,总不能给每个按钮手动起不同的引用名吧?其实咱们换个思路,不用单独命名模板引用变量也能完美实现需求,下面给你两种可行的方案:

方案一:组件类维护选中状态(推荐)

这种方式把按钮的选中状态统一放在组件类里管理,不仅能满足样式需求,还方便后续扩展其他逻辑(比如获取选中值提交表单)。

步骤1:在组件类中定义按钮选项数组

先把所有按钮的配置信息(值、翻译键、默认选中状态)整理成一个数组:

import { Component } from '@angular/core';
import { MatButtonToggleChange } from '@angular/material/button-toggle';

@Component({
  // 组件元信息省略
})
export class YourComponent {
  // 定义按钮选项数组
  toggleOptions = [
    { value: 'yesterday', key: 'GENERAL_KEYS.FILTER_PARAMS.YESTERDAY', checked: false },
    { value: 'today', key: 'GENERAL_KEYS.FILTER_PARAMS.TODAY', checked: true },
    { value: 'tomorrow', key: 'GENERAL_KEYS.FILTER_PARAMS.TOMORROW', checked: false }
  ];

  // 处理按钮组的变更事件
  toggleChange(event: MatButtonToggleChange) {
    const selectedValues = event.value;
    // 因为开启了multiple模式,value是数组,更新对应选项的选中状态
    this.toggleOptions.forEach(option => {
      option.checked = Array.isArray(selectedValues) 
        ? selectedValues.includes(option.value) 
        : option.value === selectedValues;
    });
  }
}

步骤2:模板中用*ngFor循环渲染按钮

直接绑定数组里的属性到按钮上,ngClass也直接根据数组项的checked值判断:

<mat-button-toggle-group 
  class="d-flex align-items-center" 
  #group="matButtonToggleGroup" 
  multiple 
  (change)="toggleChange($event)"
>
  <mat-button-toggle 
    *ngFor="let option of toggleOptions"
    [value]="option.value"
    [checked]="option.checked"
    [ngClass]="{'accent': option.checked}"
  >
    <span>{{ option.key | translate }}</span>
  </mat-button-toggle>
</mat-button-toggle-group>

方案二:模板内使用通用模板引用变量

如果不想在组件类里维护状态,也可以直接在*ngFor里用一个通用的模板引用变量,每个循环项里的变量都是独立的,不会冲突:

<mat-button-toggle-group 
  class="d-flex align-items-center" 
  #group="matButtonToggleGroup" 
  multiple 
  (change)="toggleChange($event)"
>
  <mat-button-toggle 
    *ngFor="let option of toggleOptions"
    [value]="option.value"
    [checked]="option.checked"
    #toggle="matButtonToggle"
    [ngClass]="{'accent': toggle.checked}"
  >
    <span>{{ option.key | translate }}</span>
  </mat-button-toggle>
</mat-button-toggle-group>

这里的#toggle="matButtonToggle"会在每个循环迭代中指向当前的mat-button-toggle实例,直接用toggle.checked就能拿到当前按钮的选中状态,完全不需要给每个按钮单独命名。

备注:内容来源于stack exchange,提问作者masoud khorshidi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 09:22:58