无需TS文件,如何在HTML中判断Angular Material List Option选中状态
无需TS文件的实现方案
可以通过模板引用变量直接在模板中完成判断,不需要在TS文件里处理选中状态,具体实现如下:
- 给
<mat-selection-list>添加模板引用变量(比如#selectionList) - 在目标
<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
相关产品推荐
相关产品推荐

