【问题标题】:Angular2 ngFor how to count the number of looping values?Angular2 ngFor如何计算循环值的数量?
【发布时间】:2017-09-12 15:03:39
【问题描述】:

我正在使用 ngFor 循环 8 个 json 对象,我不仅想循环值,还想计算循环值的数量并显示数字。

例如, 如果 json 值为

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

我不仅想显示“内容”的循环值,还想对它们进行计数,以便结果如下所示。

1 <- counting
Content1

2
Content2

3
Content3

4
Content4

5
Content5

6
Content6

7
Content7

8
Content8

【问题讨论】:

    标签: json angular ngfor


    【解决方案1】:

    遍历数组

    关于文档: https://angular.io/guide/structural-directives#inside-ngforhttps://angular.io/api/common/NgForOf

    假设你有一个可迭代对象:

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

    然后你可以迭代和计数:

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

    遍历对象属性

    如果你想迭代一个对象而不是一个对象数组,请检查How to iterate object keys using *ngFor

    为了记录,您需要一个自定义管道:

    @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]);
        }
    }
    

    那就是

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

    更新

    从 Angular 6.1+ 开始,您可以使用原生 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

    记录在案:

    <li *ngFor="let item of data | keyvalue; let i = index">
      {{i+1}}. {{item.key}} - {{item.value}}
    </li>
    

    【讨论】:

      【解决方案2】:

      Demo

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

      您可以只打印 items 数组的长度。

      【讨论】:

        【解决方案3】:

        我同意上述答案,但我想提供创建动态内容的详细信息,以便更好地在组件中创建逻辑,请参见以下代码: 我想在一个 div 中显示 6 个项目,并在另一个 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);
              }
            });
          }
        );
        

        }

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

        【讨论】:

          【解决方案4】:

          有一个名为count的局部变量。

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

          【讨论】:

            猜你喜欢
            • 2017-07-01
            • 1970-01-01
            • 1970-01-01
            • 2017-07-26
            • 2018-12-27
            • 2021-09-09
            • 2016-10-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多