html - 在选择框中显示具有多个分组的数组
问题描述
我正在尝试在具有 2 个分组级别的选择框中显示数组中的数据,请参见下面的屏幕截图:
但是,我找不到按软件和类型进行分组的方法,因此在此示例中,“Test”和“Test2”在相同的标题下依次显示。
我的代码如下:
HTML:
<select size=20>
<optgroup *ngFor="let item of items" label="{{item.software | uppercase}}">
<option disabled class="pl-1">{{item.type | uppercase}}</option>
<option class="pl-4">{{item.name | titlecase}}</option>
</optgroup>
</select>
打字稿:
getItems() {
this.helper.getItems((data: Array<Item>) => {
this.items = data;
this.items.forEach((item: Item) => {
item.software = 'SoftwareA';
item.type = 'TypeA';
});
});
}
无论如何这可以做到吗?任何帮助将不胜感激。
示例数据:
items = [
{
groupKey: 'SoftwareA', data: [
{ type: 'test1', name: 'A' },
{ type: 'test1', name: 'B' },
{ type: 'test2', name: 'C' },
{ type: 'test2', name: 'D' },
{ type: 'test3', name: 'E' },
]
},
]
期望的结果:
解决方案
您可以只使用组中的两个 ngFor 一个和其他 fro 选项元素,因此例如数据可以如下所示
items = [
{
groupKey: 'SoftwareA', data: [
{ type: 'test1' },
{ type: 'test2' },
{ type: 'test3' },
]
},
{
groupKey: 'SoftwareB', data: [
{ type: 'test6' },
{ type: 'test7' },
{ type: 'test8' },
]
},
]
我发现上面的结构更容易在模板上使用
模板
<select size=20>
<optgroup *ngFor="let item of items" label="{{item.groupKey | uppercase}}">
<option *ngFor="let optionData of item.data" class="pl-4">
{{optionData.type | titlecase}}
</option>
</optgroup>
</select>
更新
因为我们不能拥有超过一个级别,所以我们可以在将 spisific otpion 作为组之前设置一个禁用选项,并将禁用设置为 true,这样它就不能被选中
items = [
{
groupKey: 'SoftwareA', data: [
{ type: 'test1' , groupKey:true },
{ type: 'test1', name:'A' },
{ type: 'test2' , groupKey:true },
{ type: 'test2', name:'B' },
{ type: 'test2', name:'C' },
{ type: 'test3' , groupKey:true },
{ type: 'test3', name:'D' },
{ type: 'test3', name:'E' },
]
},
]
模板
<select size=20>
<optgroup *ngFor="let item of items" label="{{item.groupKey | uppercase}}">
<ng-container *ngFor="let optionData of item.data">
<option *ngIf=" optionData.groupKey;else dataOptionElem" class="header" [disabled]="true">
{{optionData.type | titlecase}}
</option>
<ng-template #dataOptionElem>
<option class="pl-4">{{optionData.name}}</option>
</ng-template>
</ng-container>
</optgroup>
</select>
风格
option.pl-4 {
padding-left: 0.8rem;
display: block;
}
.header {
font-weight: bold;
color : #000;
}