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

如何让Angular mat-selection-list实现单选(类似单选按钮效果)

让Angular的mat-selection-list实现单选效果

我来帮你搞定这个需求!要把默认多选的mat-selection-list改成单选(和单选按钮组效果一致),有两种实用的方法,你可以根据场景选择:

方法一:利用官方multiple属性(推荐)

这是最简洁的方式,因为mat-selection-list本身就提供了multiple输入属性来控制是否允许多选,默认值是true,我们只需要把它设为false就能自动开启单选模式:

模板代码

<!-- 绑定ngModel来获取选中值,同时设置multiple为false -->
<mat-selection-list [(ngModel)]="selectedOption" [multiple]="false">
  <!-- 循环渲染选项 -->
  <mat-list-option 
    *ngFor="let option of options" 
    [value]="option"
  >
    {{ option.label }}
  </mat-list-option>
</mat-selection-list>

组件类代码

只需要定义选项数组和选中值变量,不需要额外的事件处理逻辑:

import { Component } from '@angular/core';

@Component({
  selector: 'app-single-select-list',
  templateUrl: './single-select-list.component.html',
  styleUrls: ['./single-select-list.component.css']
})
export class SingleSelectListComponent {
  // 定义选项集合
  options = [
    { value: 'option1', label: '选项1' },
    { value: 'option2', label: '选项2' },
    { value: 'option3', label: '选项3' }
  ];
  // 存储选中的选项
  selectedOption: any;
}

方法二:自定义选中事件逻辑(适合需要额外处理的场景)

如果你的需求中,选中选项时需要执行一些额外的业务逻辑(比如发起请求、更新其他数据),可以通过监听selectionChange事件来手动控制单选:

模板代码

<mat-selection-list [(ngModel)]="selectedOption" (selectionChange)="handleSelection($event)">
  <mat-list-option 
    *ngFor="let option of options" 
    [value]="option"
  >
    {{ option.label }}
  </mat-list-option>
</mat-selection-list>

组件类代码

在事件处理方法中,先取消所有选项的选中状态,再选中当前点击的选项:

import { Component } from '@angular/core';
import { MatSelectionListChange } from '@angular/material/list';

@Component({
  selector: 'app-single-select-list',
  templateUrl: './single-select-list.component.html',
  styleUrls: ['./single-select-list.component.css']
})
export class SingleSelectListComponent {
  options = [
    { value: 'option1', label: '选项1' },
    { value: 'option2', label: '选项2' },
    { value: 'option3', label: '选项3' }
  ];
  selectedOption: any;

  handleSelection(event: MatSelectionListChange) {
    // 1. 取消所有选项的选中状态
    event.source.deselectAll();
    // 2. 选中当前点击的选项
    event.option.selected = true;
    // 3. 更新绑定的选中值(如果需要)
    this.selectedOption = event.option.value;

    // 这里可以添加你的额外业务逻辑,比如:
    // console.log('选中了:', this.selectedOption);
    // this.someService.updateData(this.selectedOption);
  }
}

注意事项

别忘了在你的模块中导入MatListModule,同时如果用ngModel的话,也要确保导入了FormsModule或ReactiveFormsModule,否则组件无法正常使用:

import { MatListModule } from '@angular/material/list';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule,
    MatListModule
  ]
})
export class YourFeatureModule { }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:25:48