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

如何让Angular的mat-chip-listbox始终保留至少一个选中值

配置Angular mat-chip-listbox确保至少保留一个选中值

如果你的mat-chip-listbox是多选模式(需通过[multiple]="true"开启),要避免用户取消所有选中选项,可以通过以下两种方式实现:

方法1:自定义表单验证器(推荐,符合Reactive Forms规范)

给对应FormControl添加自定义验证规则,强制选中选项数量≥1:

import { FormControl, Validators, AbstractControl, ValidationErrors } from '@angular/forms';

// 自定义验证器函数
function atLeastOneSelected(control: AbstractControl): ValidationErrors | null {
  const selectedValues = control.value;
  // 多选模式下value为数组,检查数组长度是否为0
  if (Array.isArray(selectedValues) && selectedValues.length === 0) {
    return { noSelection: true };
  }
  return null;
}

// 初始化表单时绑定验证器
this.yourForm = this.formBuilder.group({
  fooBar: ['', [Validators.required, atLeastOneSelected]]
});

模板中添加错误提示,让用户清楚规则:

<mat-chip-listbox
  aria-label="foo-bar"
  formControlName="fooBar"
  [multiple]="true"
>
  <mat-chip-option *ngFor="let i of fooBars" [value]="i">
    {{ i }}
  </mat-chip-option>
</mat-chip-listbox>

<!-- 显示验证错误 -->
<div *ngIf="yourForm.get('fooBar')?.hasError('noSelection')" style="color: red; margin-top: 8px;">
  至少要选择一个选项
</div>

方法2:拦截事件阻止取消最后一个选项

通过监听selectionChange事件,直接阻止用户取消最后一个选中的选项:

模板修改:

<mat-chip-listbox
  aria-label="foo-bar"
  formControlName="fooBar"
  [multiple]="true"
  #chipList="matChipListbox"
>
  <mat-chip-option 
    *ngFor="let i of fooBars" 
    [value]="i"
    (selectionChange)="onChipSelectionChange($event, chipList)"
  >
    {{ i }}
  </mat-chip-option>
</mat-chip-listbox>

组件类实现事件处理逻辑:

import { MatChipListbox, MatChipSelectionChange } from '@angular/material/chips';

onChipSelectionChange(event: MatChipSelectionChange, chipList: MatChipListbox) {
  // 判断是否是取消选中,且当前只剩这一个选中项
  if (!event.selected && chipList.selectedOptions.selected.length === 1) {
    // 强制重新选中该选项,阻止取消操作
    event.source.select();
  }
}

注意事项

  • 若使用单选模式(mat-chip-listbox默认模式),无需额外配置——单选模式下用户无法取消已选中选项,必须切换到其他选项。
  • 方法1更贴合Angular表单设计逻辑,可结合表单状态扩展更多业务;方法2更直接,适合无需验证提示的场景。

内容的提问来源于stack exchange,提问作者Raphaël Balet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:12:57