[英]Auto-insert <ion-list-divider> on change of value in *ngFor
我有一个 JSON 对象数组。 像这样的东西:
[
{ details: 'get dressed', project: 'morning', importance: 'volcanic' },
{ details: 'pour cheerios, project: 'morning', importance: 'medium' },
{ details: 'drive to work', project: 'commute', importance: 'high' },
...
{ details: 'write code', project: 'fun', importance: 'medium },
]
在我的模板中,我设置了一个 *ngFor 循环来显示每个项目。 像这样的东西:
<ion-list>
<ion-item *ngFor="let toDo of listOfToDos">
<ion-label> {{ toDo.details }} - {{ toDo.project }} </ion-label>
</ion-item>
</ion-list>
结果是一堆离子项目。 凉爽的。 我已按项目顺序对数组进行了排序。
我想要做的是插入 header、break 或其他任何内容,每次toDo.project
的值在*ngFor
循环中从项目 n 更改为项目 n+1 时。 生成的 output 将是:
早晨
穿好衣服
倒干杯
通勤
开车上班
...
乐趣
编写代码
我不知道有多少项目(列表的子部分)。
我考虑构建一个独特项目的列表,然后嵌套 *ngFor 类似这样的东西:
*ngFor="let project of projects"
*ngFor="toDo of toDos"
*ngIf="toDo.project ===project"
但这似乎效率低下。 有没有更优雅的方法来做到这一点?
谢谢大家。
保罗
检查此链接https://stackblitz.com/edit/ionic-dpwyqc?file=pages%2Fhome%2Fhome.ts
在html file
中添加这个
<ion-list>
<ng-container *ngFor="let item of data">
<ion-item-divider>
<ion-label>
{{item[0]}}
</ion-label>
</ion-item-divider>
<ion-item *ngFor="let item_sub of item[1]">
<ion-label> {{ item_sub?.details }}</ion-label>
</ion-item>
</ng-container>
</ion-list>
在ts file
中添加这个
public data: any = [
{ details: 'get dressed', project: 'morning', importance: 'volcanic' },
{ details: 'pour cheerios', project: 'morning', importance: 'medium' },
{ details: 'drive to work', project: 'commute', importance: 'high' },
{ details: 'write code', project: 'fun', importance: 'medium' },
];
constructor() {
let getData = this.groupMethod(this.data, 'project');
this.data = Object.entries(getData);
}
groupMethod(array, fn) {
return array.reduce(
(acc, current) => {
const groupName = typeof fn === 'string' ? current[fn] : fn(current);
(acc[groupName] = acc[groupName] || []).push(current);
return acc;
}, {}
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.