Angular2 ngFor how to count the number of looping values?

前端 未结 3 1088
我寻月下人不归
我寻月下人不归 2021-02-07 05:35

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,

3条回答
  •  天命终不由人
    2021-02-07 06:20

    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:

  • {{i+1}} {{item}}
  • 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

  • ...
  • 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:

  • {{i+1}}. {{item.key}} - {{item.value}}
提交回复
热议问题