【问题标题】:Auto-insert <ion-list-divider> on change of value in *ngFor在 *ngFor 中更改值时自动插入 <ion-list-divider>
【发布时间】:2021-07-11 01:00:18
【问题描述】:

我有一个 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>

结果是一堆离子物品。凉爽的。我已经按照项目的顺序对数组进行了排序。

每当toDo.project 的值在*ngFor 循环中从第n 项更改为第n+1 项时,我想要做的是插入标题、中断或其他任何内容。结果输出将是:


早上
穿好衣服
倒酒
通勤
开车上班
...
有趣
编写代码


我不知道有多少项目(列表的子部分)。

我考虑构建一个独特项目的列表,然后嵌套 *ngFor 类似这样的东西:

*ngFor="let project of projects"
  *ngFor="toDo of toDos"
    *ngIf="toDo.project ===project"

但这似乎效率低下。有没有更优雅的方法来做到这一点?

谢谢大家。

保罗

【问题讨论】:

    标签: angular list ionic-framework ngfor


    【解决方案1】:

    查看此链接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;
          }, {}
        );
      }
    

    【讨论】:

    • 完美。没有更好的词。感谢您花这么多时间准备它。了不起。
    猜你喜欢
    • 2018-09-25
    • 2019-11-28
    • 1970-01-01
    • 2019-10-01
    • 2017-10-22
    • 2017-11-23
    • 2017-11-09
    • 2020-05-15
    • 2019-01-05
    相关资源
    最近更新 更多