Angular Material嵌套选项列表问题:样式异常且键盘导航失效
嵌套选择列表样式异常与键盘导航失效问题
我尝试用Angular Material的选项列表实现带选择功能的嵌套列表,但最终样式异常,键盘导航也无法正常工作。
原始代码示例
HTML模板:
<mat-selection-list #myList> @for (prodCat of list; track prodCat.id) { <mat-list-option togglePosition="before" [lines]="prodCat.childs.length+1"> {{ prodCat.name }} <mat-selection-list > @for (subList of prodCat.childs; track subList.id){ <mat-list-option togglePosition="before"> {{subList.name}} </mat-list-option> } </mat-selection-list> </mat-list-option> } </mat-selection-list>
对应数据结构:
list = [ { id: 1, name: 'one' , childs:[{id: 11, name: 'one-one'}, {id: 12, name: 'one-two'} ]}, { id: 2, name: 'two' , childs:[{id: 21, name: 'two-one'}, {id: 22, name: 'two-two'}, {id:23, name: 'three-two'} ]}, { id: 3, name: 'three' , childs:[{id: 31, name: 'three-one'}, {id: 32, name: 'three-two'}]}, ];
问题原因
核心问题是将<mat-selection-list>直接嵌套在了<mat-list-option>内部,这不符合Angular Material组件的设计规范——<mat-selection-list>作为独立的选择容器,嵌套后会破坏内部DOM结构和交互逻辑,导致样式错乱、键盘导航失效。
修复方案
方案1:单选择列表层级缩进(轻量实现)
保持单个<mat-selection-list>,通过CSS缩进区分父子项,保留完整的键盘导航和选择功能。
修改后的HTML:
<mat-selection-list #myList> @for (prodCat of list; track prodCat.id) { <!-- 父级选项 --> <mat-list-option togglePosition="before" [value]="prodCat"> {{ prodCat.name }} </mat-list-option> <!-- 子级选项,通过样式缩进 --> @for (subList of prodCat.childs; track subList.id) { <mat-list-option togglePosition="before" [value]="subList" class="child-item"> {{ subList.name }} </mat-list-option> } } </mat-selection-list>
添加CSS样式:
.child-item { padding-left: 40px; /* 按需调整缩进距离 */ }
方案2:可折叠嵌套选择列表(复杂场景)
如果需要折叠/展开的交互,结合<mat-expansion-panel>实现严格的嵌套视觉结构,同时保证交互正常。
修改后的HTML:
<mat-selection-list #myList> @for (prodCat of list; track prodCat.id) { <mat-list-option togglePosition="before" [value]="prodCat"> <mat-expansion-panel> <mat-expansion-panel-header> <span>{{ prodCat.name }}</span> </mat-expansion-panel-header> <mat-selection-list> @for (subList of prodCat.childs; track subList.id) { <mat-list-option togglePosition="before" [value]="subList"> {{ subList.name }} </mat-list-option> } </mat-selection-list> </mat-expansion-panel> </mat-list-option> } </mat-selection-list>
说明
- 两种方案都能恢复正常的键盘导航(方向键切换、空格/回车触发选择)和选择状态管理
- 方案1适合简单层级展示,方案2适合需要折叠交互的复杂嵌套场景
内容的提问来源于stack exchange,提问作者LeO
相关产品推荐
相关产品推荐

