简体   繁体   中英

Auto-insert <ion-list-divider> on change of value in *ngFor

I have an array of JSON objects. Something like this:

[
  { 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 },
]

In my template, I have an *ngFor loop set up to show each item. Something like this:

<ion-list>
  <ion-item *ngFor="let toDo of listOfToDos">
    <ion-label> {{ toDo.details }} - {{ toDo.project }} </ion-label>
  </ion-item>
</ion-list>

and the result is a bunch of ion-items. Cool. I have sorted the array in order of project.

What I want to do is to insert a header, break, or whatever, each time the value of toDo.project changes from item n to item n+1 in the *ngFor loop. The resulting output would be:


Morning
get dressed
pour cheerios
Commute
drive to work
...
Fun
Write code


I do not know ahead of time how many projects (sub-divisions of the list) there are.

I considered building a list of unique projects and then nesting *ngFor something like this:

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

But this seems inefficient. Is there a more elegant way to do this?

Thanks all.

Paul

Check this link https://stackblitz.com/edit/ionic-dpwyqc?file=pages%2Fhome%2Fhome.ts

Add this in 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>

Add this in 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;
      }, {}
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM