How to show hide items inside ngfor loop?

Viewed 127

I have an ngFor for some content, I want to show only items in a single line rest items should be hidden and the card should expand on clicking show more.

fruits= [apple, orange, grapes, banana, strawberry, pineapple, watermelon, kiwi, avocado, papaya  ]

<div class="more">show more</div>
<div class="less">show less</div>

    <ul>
    <li *ngfor = let list of fruits>{{list}}</li>
    </ul>

here in the list i want to show only first 3 rest should be hidden and on clicking show more it should show.

5 Answers

in your .ts file

 fruits= ['apple', 'orange', 'grapes', 'banana', 'strawberry', 'pineapple', 'watermelon', 'kiwi', 'avocado', 'papaya'  ]
 indexToshow = 3;

in your HTML file.

<div *ngIf="indexToshow == 3" class="more" (click)="indexToshow = fruits.length">show more</div>
<div *ngIf="indexToshow != 3" (click)="indexToshow = 3" class="less">show less</div>
<ul>
    <ng-container  *ngFor="let list of fruits; index as i">
        <li *ngIf="i < indexToshow">{{list}}</li>
    </ng-container >
</ul>

you can replace 3 value with the limit you want.

you can try this method,

    fruits= [apple, orange, grapes, banana, strawberry, pineapple, watermelon, kiwi, avocado, papaya  ]
    removeElements = 3;

    show(){
        this.removeElements=0;
    }

    hide(){
        this.removeElements=3;
    }

    <ul>
        <li *ngfor = let list of fruits.slice(removeElements)>{{list}}</li>
    </ul>

Here is a crude answer, this adds 3 each time you click load more

HTML

<ul>
    <li *ngFor="let list of fruitView">{{list}}</li>
</ul>
<button [disabled]="fruitView?.length == fruits?.length" (click)="loadMore()">Load More</button>

Component

export class AppComponent {
public fruits = [
  "apple",
  "orange",
  "grapes",
  "banana",
  "strawberry",
  "pineapple",
  "watermelon",
  "kiwi",
  "avocado",
  "papaya"
];

public fruitView = this.fruits.slice(0, 3);

public loadMore(): void {
  this.fruitView = this.fruits.slice(
    0,
    Math.min(this.fruitView.length + 3, this.fruits.length)
  );
 }
}

https://stackblitz.com/edit/angular-ivy-dmzcd6

You can use index of the loop to show or hide based on the condition.

Check this demo

Unlike other answers, this way you won't need to slice and change the array each time you show or hide the items and hence data will always be consistent.

<tr *ngFor = "let fruit of fruits">
    <ng-template [ngIf] = "fruit"=='apple'>
        <td> show value!</td>
    </ng-template>
</tr>
Related