我有一个如下所示的 json 数组,
items=[
{name:"first",subname:"first 1"},
{name:"first",subname:"first 2"},
{name:"first",subname:"first 3"},
{name:"second",subname:"second 1"},
{name:"second",subname:"second 2"}
];
我想显示为列表,
first
first 1
first 2
first 3
second
second 1
second 2
虽然我通过在 component.ts 中放置两个函数来实现这一点
getsubname(name){
return this.items.filter(
function(data){return data.name == name}
);
}
getnames(){
var disname = this.items.map(item => item.name)
.filter((value, index, self) => self.indexOf(value) === index)
return disname
}
并将它们放在 HTML 中,如下所示,
<div>
<mat-list>
<ng-container *ngFor="let item of getnames()">
<mat-list-item>{{item}}</mat-list-item>
<mat-list style="margin-left:30px;">
<div *ngFor="let subItem of getsubname(item)">
<mat-list-item >{{ subItem.subname }}</mat-list-item>
</div>
</mat-list>
</ng-container>
</mat-list>
</div>
但是这种方法看起来很幼稚。我确信必须有更好的方法来做到这一点。请建议。