How to 'show more' rows using *ngFor

后端 未结 3 625
轻奢々
轻奢々 2021-01-14 17:27

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

{{ item.i
相关标签:
3条回答
  • 2021-01-14 17:29

    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>
    
    0 讨论(0)
  • 2021-01-14 17:42

    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.

    0 讨论(0)
  • 2021-01-14 17:52

    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>
    
    0 讨论(0)
提交回复
热议问题