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

无需TS文件,如何在HTML中判断Angular Material List Option选中状态

无需TS文件的实现方案

可以通过模板引用变量直接在模板中完成判断,不需要在TS文件里处理选中状态,具体实现如下:

  1. 给<mat-selection-list>添加模板引用变量(比如#selectionList)
  2. 在目标<div>的*ngIf中,通过该引用变量检查选中项里是否包含"New User"

完整代码示例:

<mat-selection-list #selectionList (selectionChange)="onApplicationSelection(14, $event.options)">
  <mat-list-option class="col-md-3" checkboxPosition="before" value="New User">New User</mat-list-option>
  <mat-list-option class="col-md-3" checkboxPosition="before" value="Change to existing user">Change to existing user</mat-list-option>
</mat-selection-list>

<div *ngIf="selectionList.selectedOptions.selected.some(opt => opt.value === 'New User')">
  <!-- 这里放置需要渲染的内容 -->
</div>

原理说明

<mat-selection-list>的selectedOptions属性是SelectionModel类型,它的selected数组会实时同步当前选中的所有<mat-list-option>实例。我们通过数组的some()方法遍历选中项,只要有一个选项的value匹配"New User",就会返回true,触发<div>的渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:40:25