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

Angular Material mat-selection-list能否绑定对象数组?

解决Mat Selection List对象数组不工作的问题

嘿,你的问题其实很容易搞定——模板引用变量和组件里的数组变量重名了!你在<mat-selection-list>上定义了#errorList,但组件类里的对象数组也叫errorList,这就导致模板里的*ngFor循环和后面统计选中数量的代码,都错误地指向了这个列表组件的引用,而不是你定义的对象数组数据。

修复步骤:

  • 把<mat-selection-list>的模板引用变量改成别的名字(比如#errorSelectionList),避免和组件变量冲突
  • 调整统计选中数量的代码,使用新的引用变量来获取选中项

修改后的完整模板代码:

<mat-selection-list #errorSelectionList class="area-block ">
  <mat-list-option *ngFor="let err of errorList " style="color: #000000;">
    {{err.type}}
  </mat-list-option>
</mat-selection-list>
<p style="color: #000000;" class="area-block"> Options selected: {{errorSelectionList.selectedOptions.selected.length}} </p>

额外优化:绑定选中状态到对象属性

如果希望列表项的选中状态和你对象里的selected属性同步,可以给<mat-list-option>加上双向绑定:

<mat-selection-list #errorSelectionList class="area-block ">
  <mat-list-option *ngFor="let err of errorList " 
                   style="color: #000000;"
                   [(selected)]="err.selected">
    {{err.type}}
  </mat-list-option>
</mat-selection-list>

这样当用户选中/取消选中列表项时,对应对象的selected属性会自动更新;反过来,如果代码里修改了对象的selected值,列表项的选中状态也会同步变化。

放心,Mat Selection List完全支持对象数组,只是变量名冲突导致数据没正确绑定上~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:18:33