Angular修改mat-button-toggle-group实现支持取消选中的功能
你可以完全通过响应式表单控件控制值,不需要从事件对象里手动获取父组件实例,以下是两种可行实现:
方案一:给每个按钮绑定点击事件(适合固定少量选项)
模板调整
<mat-button-toggle-group formControlName="myCtl" class="col2 v-toggle short formAnswer" aria-label="Font Style"> <mat-button-toggle [value]="true" (click)="$event.preventDefault(); onToggleClick(true)">Yes</mat-button-toggle> <mat-button-toggle [value]="false" (click)="$event.preventDefault(); onToggleClick(false)">No</mat-button-toggle> </mat-button-toggle-group>
这里加$event.preventDefault()是为了阻止组件默认的单选赋值逻辑,完全自己控制值的更新逻辑,避免冲突。
组件TS代码
// 替换代码里yourFormGroup为你自己定义的FormGroup变量名 onToggleClick(clickedValue: boolean): void { const myControl = this.yourFormGroup.get('myCtl'); const currentValue = myControl?.value; if (currentValue === clickedValue) { // 点击已选中选项,重置为未选中状态 myControl.setValue(null); } else { // 点击未选中选项,更新为对应值 myControl.setValue(clickedValue); } }
方案二:绑定组点击事件(适合动态生成大量选项)
如果你的选项是ngFor动态生成的,不需要每个按钮单独绑事件,通过模板引用获取组件实例即可:
模板调整
<mat-button-toggle-group #toggleGroup formControlName="myCtl" (click)="choiceClick($event)" class="col2 v-toggle short formAnswer" aria-label="Font Style"> <mat-button-toggle [value]="true">Yes</mat-button-toggle> <mat-button-toggle [value]="false">No</mat-button-toggle> </mat-button-toggle-group>
组件TS代码
import { MatButtonToggleGroup } from '@angular/material/button-toggle'; // ... // 取到toggle组的实例 @ViewChild('toggleGroup') toggleGroup!: MatButtonToggleGroup; choiceClick(event: MouseEvent): void { // 匹配点击的toggle按钮元素 const toggleElement = (event.target as HTMLElement).closest('mat-button-toggle'); if (!toggleElement) return; // 匹配对应的按钮实例,拿到value const clickedToggle = this.toggleGroup.buttons.find(t => t._elementRef.nativeElement === toggleElement); if (!clickedToggle) return; const clickedValue = clickedToggle.value; const myControl = this.yourFormGroup.get('myCtl'); const currentValue = myControl?.value; // 阻止默认赋值逻辑 event.preventDefault(); event.stopPropagation(); if (currentValue === clickedValue) { myControl.setValue(null); } else { myControl.setValue(clickedValue); } }
内容的提问来源于stack exchange,提问作者user6269972
相关产品推荐
相关产品推荐

