How to 'show more' rows using *ngFor

2020-03-26 07:14发布

问题:

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

回答1:

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.



回答2:

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>


回答3:

Use <ng-container> (which will not create any additional nodes) as follows

<div class="table">
  <ng-container *ngFor="let item of list; index as i">
    <div *ngIf="i<3 || more" class="row">
      {{ item.id }} {{ item.name }}
    </div>
  <ng-container>
</div>

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


标签: angular