最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add a condition for ngFor loop - Stack Overflow

programmeradmin0浏览0评论

I am creating a table using Clarity. They have their own syntax, clrDgItems, but the structure is the same as ngFor.

I want to create an loop for my table, which filters the first 10 items, and then a second table which only shows items 11-20.

You should also be able to go to the next page. That will say, first table to update to items 21-30 and second table to 31-40

My first thoughts was something like,

ngFor="let employee of employees; i as index; i < firstMaxIndex;"
ngFor="let employee of employees; i as index; i > firstMaxIndex && i < secondMaxIndex"

But ngFor loop doesnt work like that, and I get the error: NG5002: Parser Error: Unexpected token <

I am creating a table using Clarity. They have their own syntax, clrDgItems, but the structure is the same as ngFor.

I want to create an loop for my table, which filters the first 10 items, and then a second table which only shows items 11-20.

You should also be able to go to the next page. That will say, first table to update to items 21-30 and second table to 31-40

My first thoughts was something like,

ngFor="let employee of employees; i as index; i < firstMaxIndex;"
ngFor="let employee of employees; i as index; i > firstMaxIndex && i < secondMaxIndex"

But ngFor loop doesnt work like that, and I get the error: NG5002: Parser Error: Unexpected token <

Share Improve this question edited Jul 20, 2021 at 7:50 Sebastian Ciocarlan 3002 silver badges13 bronze badges asked Jul 20, 2021 at 7:04 Robin LindgrenRobin Lindgren 801 silver badge9 bronze badges 6
  • I suppose next statement can be condition, would that won't help instead of clubbing them together? – Bharat Commented Jul 20, 2021 at 7:08
  • Do you might explain more detail? – Apple Yellow Commented Jul 20, 2021 at 7:08
  • The condition should go inside *ngFor context, like this: <div *ngIf="i < firstMaxIndex">...</div> – lbsn Commented Jul 20, 2021 at 7:09
  • @Bharat You right, I am used to for-loops in C#, where the condition and declare is in the same parameters! – Robin Lindgren Commented Jul 20, 2021 at 7:12
  • 1 @Abinesh already posted it :). To me it makes more clean and readable code, like splitting the loop and condition as two different responsibilities. – Bharat Commented Jul 20, 2021 at 7:17
 |  Show 1 more ment

2 Answers 2

Reset to default 4

It's better to separate out the condition and loop as below:

<ng-container *ngFor="let employee of employees; i as index;">
    <div *ngIf="i > firstMaxIndex && i < secondMaxIndex">
        // add elements or display values based on your needs.
    </div>
</ng-container>

Use slice

{{ value_expression | slice : start [ : end ] }}

So like this:

ngFor="let employee of employees | slice : 0 : firstMaxIndex"

ngFor="let employee of employees | slice : firstMaxIndex : secondMaxIndex"
发布评论

评论列表(0)

  1. 暂无评论