简体   繁体   English

如何在 ngfor 循环中显示隐藏项?

[英]How to show hide items inside ngfor loop?

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.我有一些内容的 ngFor,我只想显示一行中的项目 rest 项目应该被隐藏,卡片应该在点击显示更多时展开。

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.在列表中我只想显示第一个 3 rest 应该被隐藏,点击显示更多它应该显示。

in your.ts file在你的.ts 文件中

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

in your HTML file.在您的 HTML 文件中。

<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.你可以用你想要的限制替换 3 值。

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这是一个粗略的答案,每次单击加载更多时都会增加 3

HTML 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 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM