Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'show more' rows using *ngFor

Tags:

angular

I have the following code (simplified in head - not tested)

<div class="table">
  <div *ngFor="let item of list" class="row">
    {{ item.id }} {{ item.name }}
  </div>
</div>

<button (click)="more = !more">{{ more ? 'less':'more' }}</button>

I want to show only the first 3 list items at the beginning - and when user clicks "more", I want to show all the list items. How to do it?

UPDATE

More details about performance for this case are here and here

like image 245
Kamil Kiełczewski Avatar asked Dec 17 '22 14:12

Kamil Kiełczewski


2 Answers

Another approach using the SlicePipe:

<div class="table">
  <div *ngFor="let item of list | slice:0:(more ? undefined : 3)" class="row">
    {{ item }}
  </div>
</div>

<button (click)="more = !more">{{ more ? 'less':'more' }}</button>

Also, use of instead of in with *ngFor.

like image 131
naeramarth7 Avatar answered Jan 25 '23 22:01

naeramarth7


You can use slicePipe to create a new array containing a subset an array.

<div class="table">
  <div *ngFor="let item of (more ? list : (list|slice:0:3))" class="row">
      {{ item.id }} {{ item.name }}
  <div>
</div>

<button (click)="more = !more">{{ more ? 'less' : 'more' }}</button>
like image 25
Reactgular Avatar answered Jan 25 '23 22:01

Reactgular