1

Here's the code for the accordion:

<ngb-accordion [closeOthers]="false" activeIds="0">
        <ng-container class="card" *ngFor="let post of Posts">
            <ngb-panel title="{{post.title}} - By: {{post.author}}, At: {{post.datePosted}}" id="{{post.id}}">
                <ng-template ngbPanelContent>
                    {{post.about}}
                    <hr>
                    <button (click)="navigateTo(post.id)" type="button" class="btn btn-link">Comments</button>
                </ng-template>
            </ngb-panel>
        </ng-container>
    </ngb-accordion>

What I'd like to do is basically sorting the accordion's content by {{post.datePosted}} so the first item in the list would be the one posted recently.

If you have any ideas or suggestions... please.
Right now I store the dates int he Posts array like this:

var x = new Date();
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
var h = x.getHours().toString();
var min = x.getMinutes();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
var date = y+"." + m+"." + d+" "+h+":"+min;

And the array definition:

export class Post {
  id: number;
  cim: string;
  leir: string;
  iro: string;
  mikor: number;
}

2 Answers2

0

IMHO, you will have to sort the data in the .ts file itself and then display in the front-end like this:

In .ts file:

let sortedPosts = this.Posts.sort((a, b) => (new Date(a.datePosted).getTime() - new Date(b.datePosted).getTime()));     

In .html use sortedPosts instead of Posts like this:

<ngb-accordion [closeOthers]="false" activeIds="0">
        <ng-container class="card" *ngFor="let post of sortedPosts">
            <ngb-panel title="{{post.title}} - By: {{post.author}}, At: {{post.datePosted}}" id="{{post.id}}">
                <ng-template ngbPanelContent>
                    {{post.about}}
                    <hr>
                    <button (click)="navigateTo(post.id)" type="button" class="btn btn-link">Comments</button>
                </ng-template>
            </ngb-panel>
        </ng-container>
    </ngb-accordion>            

For more info on date comparison see this.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
  • I see, then so I have to store the datePosted's in an integer? Because now it's something like this:var x = new Date(); var y = x.getFullYear().toString(); var m = (x.getMonth() + 1).toString(); var d = x.getDate().toString(); var h = x.getHours().toString(); var min = x.getMinutes(); (d.length == 1) && (d = '0' + d); (m.length == 1) && (m = '0' + m); var date = y+"." + m+"." + d+" "+h+":"+min; –  Jul 13 '18 at 13:40
  • @Skickpause not necessarily. You can use `new Date()` as constructor. Updated my answer. – BlackBeard Jul 13 '18 at 13:42
  • Thank you captain! You have my greatest deepest gratitude. :) –  Jul 13 '18 at 13:55
0

import * as _ from 'lodash'; this.sortedPosted= _.sortBy(this.posts, p => p.datePosted);

xxxerneaxx
  • 49
  • 1
  • 3