19

I am using ngFor to loop 8 json objects and I want not only to loop the values but also I want to count the number of looping values and display the number.

For example, if json value is

Content:{
0:"Content1",
1:"Content2",
2:"Content3",
3:"Content4",
4:"Content5",
5:"Content6",
6:"Content7",
7:"Content8"
}

I not only want to display looping values of 'Content', but I also want to count them so that the result could be this below.

1 <- counting
Content1

2
Content2

3
Content3

4
Content4

5
Content5

6
Content6

7
Content7

8
Content8
Lea
  • 1,245
  • 5
  • 22
  • 31

4 Answers4

41

Iterating over array

Regarding the docs: https://angular.io/guide/structural-directives#inside-ngfor and https://angular.io/api/common/NgForOf

Say you have an iterable:

let content = [
  "Content1",
  "Content2",
  "Content3",
  "Content4",
  "Content5",
  "Content6",
  "Content7",
  "Content8"
]

Then you can iterate and count with:

<li *ngFor="let item of content; let i = index">
    {{i+1}} {{item}}
</li>

Iterating over object properties

If you want to iterate over an object rather than an array of objects, check How to iterate object keys using *ngFor

For the record, you need a custom pipe:

@Pipe({ name: 'keys',  pure: false })
export class KeysPipe implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)//.map(key => value[key]);
    }
}

So that would be

<li *ngFor="let key of objs | keys; let i = index"> ...

Update

From Angular 6.1+, you can use the native KeyValuePipe.

https://blog.angular.io/angular-v6-1-now-available-typescript-2-9-scroll-positioning-and-more-9f1c03007bb6#ff4b

https://angular.io/api/common/KeyValuePipe

For the record:

<li *ngFor="let item of data | keyvalue; let i = index">
  {{i+1}}. {{item.key}} - {{item.value}}
</li>
aldo.roman.nurena
  • 1,323
  • 12
  • 26
9

Demo

<ul>
  <li *ngFor="let item of items; let i = index">
    {{i}}. {{item}}
  </li>
</ul>
{{items ? items.length : ''}}

You could just print the length of the items array.

Andrei Voicu
  • 740
  • 1
  • 6
  • 13
2

There is a local variable named count.

<li *ngFor="let user of users; count as c">
  {{c}} is number of iterable thing 
</li>
gelevanog
  • 150
  • 5
1

I agree with above answer, but I would like to provide details for creating dynamic content its better to create your logic in component see below code: I want to display 6 items in one div and remaining in another div

component.ts:

  getMyTasksDueToday(url,duedate){
console.log(this.currentDate);
this.dashboardservices.getGroupedTasksByDueDate(url,duedate).subscribe(
  (modelData: ITasks[]) => {
    //console.log(modelData);
    this._myTasksDueToday = modelData;
    let arr1 = [];
    let arr2 = [];
    let i = 1;
    modelData.forEach((item)=>{
      //console.log(item);
      if(i<=6){
        arr1.push(item);
      }else{
        this._myTasksDueToday_hasPart2 = true;
        arr2.push(item);
      }
      i++;
    });
    this._myTasksDueToday_part1 = arr1;
    this._myTasksDueToday_part2 = arr2;
    //this._myTasksDueToday_part3 = arr3;

    
  },
  error => {
    const res = this.dialogService.ErrorDialog('Server Error', 'Sorry, the system is unavailable at the moment.', 'Close', 'Try again');
    res.afterClosed().subscribe(dialogResult => {
      if (dialogResult) {
        //this.callNext(200);
      }
    });
  }
);

}

and in component.html:

     <mat-card>
              <mat-card-header>
                  <span>Due Today</span>
              </mat-card-header>
              <mat-card-content class="task-buttons-content-div">
                <div fxLayout="row wrap" fxLayoutAlign="space-between">
                  <div  >
                    <div  *ngFor="let rec of _myTasksDueToday_part1"  class="btn-div">
                      <button mat-raised-button color="warn" 
                        [matBadge]="rec.totaltasks" matBadgePosition="after" matBadgeColor="accent" class="btn-tasks" [routerLink]="['/tasks/alltasks/category/', rec.CategoryID,currentDate]">{{rec.CategoryName}}
                      </button>
                    </div>
                  </div>
                  <div  >
                    <div  *ngFor="let rec of _myTasksDueToday_part2"  class="btn-div">
                      <button mat-raised-button color="warn" 
                        [matBadge]="rec.totaltasks" matBadgePosition="after" matBadgeColor="accent" class="btn-tasks" [routerLink]="['/tasks/alltasks/category/', rec.CategoryID,currentDate]">{{rec.CategoryName}}
                      </button>
                    </div>
                  </div>
          
                </div>
                <div class="aligncenter">
                  <button mat-mini-fab color="accent" [routerLink]="['/tasks/alltasks/category/', all,currentDate]">All</button>
                </div>
              </mat-card-content>
            </mat-card>
MJ X
  • 8,506
  • 12
  • 74
  • 99