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

如何在单选模式的Angular Material selection-list中取消选中list-option?

实现方案

这个需求可以直接基于现有Angular Material组件实现,无需更换技术栈或从零开发,实现逻辑如下:

步骤1:修改模板代码

给mat-selection-list添加模板引用,同时为每个mat-list-option绑定点击事件:

<mat-selection-list [multiple]="false" #selectionList>
  <mat-list-option [value]="1" (click)="handleOptionClick(selectionList, $event)">Option 1</mat-list-option>
  <mat-list-option [value]="2" (click)="handleOptionClick(selectionList, $event)">Option 2</mat-list-option>
  <mat-list-option [value]="3" (click)="handleOptionClick(selectionList, $event)">Option 3</mat-list-option>
</mat-selection-list>

如果你的选项是动态生成的,直接用*ngFor循环渲染即可,逻辑通用。

步骤2:编写组件逻辑

在对应的ts文件中添加点击事件处理逻辑:

import { Component } from '@angular/core';
import { MatSelectionList, MatListOption } from '@angular/material/list';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  handleOptionClick(list: MatSelectionList, event: MouseEvent) {
    // 获取当前点击的选项元素
    const targetEl = event.target as HTMLElement;
    const clickedOption = targetEl.closest('mat-list-option') as MatListOption | null;
    if (!clickedOption) return;
    
    // 如果点击的是已经选中的选项,直接取消选中
    if (clickedOption.selected) {
      clickedOption.selected = false;
      list.selectedOptions.clear();
    }
  }
}

逻辑说明

  • 该实现完全兼容原有单选逻辑:点击未选中的选项时,会正常触发单选切换,自动取消其他选项的选中状态
  • 只有点击当前处于选中状态的选项时,才会触发取消选中的逻辑,完全匹配需求
  • 整体实现仅增加了几行业务代码,无需修改组件底层,维护成本极低,完全不需要替换为其他UI库或自行开发组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:54:03