如何不使用optgroup对下拉选择框中*ngFor遍历的数据进行分组
解决方案
1. 先在TypeScript层预处理数据
我们先把接口返回的属性项按分组字段(示例用的是AttributeName,可根据你的实际字段调整)聚合,再把分组标题作为特殊项插入到选项列表中,加标识区分普通选项和分组标题:
// 定义存储处理后分组选项的数组 groupedOptions: any[] = []; getProducts() { if (this.products.length < 1) { this.productService.getProducts().subscribe(p => { this.masterProductAttributeItems = p.MasterProductAttributeItems; // 开始分组处理 const groupMap = this.masterProductAttributeItems.reduce((result, item) => { const groupKey = item.AttributeName; if (!result[groupKey]) { result[groupKey] = []; } result[groupKey].push(item); return result; }, {}); // 拼接分组标题和对应选项 this.groupedOptions = []; Object.keys(groupMap).forEach(groupName => { // 插入分组标题项,加isGroup标识 this.groupedOptions.push({ isGroup: true, groupName: groupName }); // 插入当前分组下的所有可选选项 this.groupedOptions.push(...groupMap[groupName]); }); }); } }
2. 修改HTML模板渲染逻辑
遍历处理好的groupedOptions数组,通过isGroup标识判断渲染分组标题还是普通选项,分组标题设置disabled不可选,也可以加自定义样式区分层级:
<select class="form-control input-sm"> <ng-container *ngFor="let item of groupedOptions"> <!-- 分组标题:不可选,可自定义样式突出分组 --> <option *ngIf="item.isGroup" disabled style="font-weight:bold;background:#f5f5f5;"> {{ item.groupName }} </option> <!-- 普通可选选项,可加缩进区分层级 --> <option *ngIf="!item.isGroup" value="{{ item.MasterProductAttributeItemId }}" style="padding-left:16px;"> {{ item.Name }} </option> </ng-container> </select>
补充说明
如果需要调整分组的依据,修改reduce里的groupKey取值即可,样式也可以根据设计需求调整,不需要额外引入optGroup标签就能实现分组展示效果。
内容的提问来源于stack exchange,提问作者Pirlo
相关产品推荐
相关产品推荐

