0

How can I get last 5 records from database?

logs.component.html

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Date</th>
            <th>Logging in is completed?</th>   
        </tr>
    </thead>
    <tbody> 
        <tr *ngFor="let log of logs">
            <td>{{log.date}}</td>
            <td>{{log.isCompleted}}</td>
        </tr>
    </tbody>
</table>

With above code I get all records. I would like to do something similar to:

for (int i=logs.length(); i>logs.length()-5; i--)
Andrew Halil
  • 1,195
  • 15
  • 15
  • 21
Mateusz
  • 1,163
  • 2
  • 13
  • 25
  • 1
    You might want to filter the results at the database level, rather than in your JavaScript, as it's more efficient. Otherwise, your Angular2 app will download unnecessary data from the server, only to ignore it – Andy-Delosdos Aug 26 '16 at 08:38

4 Answers4

0

For limiting the output of NGFor see this answer: Angular 2: how to apply limit to *ngFor?

If you don't do anything particular with the rest of the data, please refer to to @Delosdos Comment: You should consider filtering the datatset on server-side.

Community
  • 1
  • 1
jbin
  • 166
  • 5
0

I did it that way:

  <tr *ngFor="let log of logs; let i =index">

                    <td *ngIf ="i>=logs.length -5">{{log.date}}</td>
                    <td * ngIf="i>=logs.length -5">{{log.isCompleted}}</td>

            </tr>
Mateusz
  • 1,163
  • 2
  • 13
  • 25
0

Angular 2 provides the Slice Pipe for subsets of a List or String expression.

array_or_string_expression | slice:start[:end]

Example:

<tr *ngFor="let log of logs | slice:0:4">
    <td >{{log.date}}</td>
    <td >{{log.isCompleted}}</td>
</tr>

Note: start and end are zero-based.

0

use following code line to get last 5 records.

logs.slice(Math.max(logs.length - 5, 1));