将数组拆分为模板Angular 2中的网格视图

时间:2017-03-20 11:49:27

标签: angular angular2-template

我有一组图像,我想将它们显示为网格10x10(表格)。我该如何实现呢?

我尝试过类似的东西,但语法错误:

.controller('Ctrl_2',function($rootScope){  
alert("what is my value? " + $rootScope.myValue);
})

2 个答案:

答案 0 :(得分:0)

一种解决方案是将数据块化为每行的数组,然后使用嵌套的*ngFor循环来迭代它们。这可以通过自定义管道来实现

<table>
  <tr *ngFor="let row of avatars | chunk: 10)">
    <td *ngFor="let avatar of row">
      <img class="img-avatar img-avatar48" [src]="avatar.avatarUri" [alt]="avatar.keywords" />
    </td>
  </tr>
</table>

chunk管道可以使用lodash _.chunk,也可以在下面原生显示:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'chunk'
})
export class ChunkPipe implements PipeTransform {

    transform(value: any, n: number): any {
        return this.chunk(value, n);
    }

    chunk(arr, n) {
        let newArr = [];
        let nestedArr = [];
        for (let i = 1; i <= arr.length; i++) {
            nestedArr.push(arr[i - 1]);
            if (i % n === 0) {
                newArr.push(nestedArr);
                nestedArr = [];
            }
        }
        if (nestedArr.length > 0) {
            newArr.push(nestedArr);
        }
        return newArr;
    }
}

答案 1 :(得分:-1)

您的代码包含额外的tr就像这样

 <ng-container *ngFor="let avatar of avatars; let i = index">
    <ng-container *ngIf="i % 10 === 0 && i === 0">
        <tr>
    </ng-container>
    <ng-container>
        <td class="text-center">
            <img class="img-avatar img-avatar48" [src]="avatar.avatarUri" [alt]="avatar.keywords" />
        </td>
    </ng-container>
    <ng-container *ngIf="i % 10 === 0">
        </tr>
    </ng-container>
</ng-container>