首页 文章

Angular2:ng表格中每行多个对象[重复]

提问于
浏览
5

这个问题在这里已有答案:

我的组件有一个我想在表中显示的字符串数组 . 但是,我希望表每行有4列 . 如何使用* ngFor每行显示4个字符串?

我知道有没有使用表的解决方案,但在这种情况下我真的很想使用表 .

3 回答

  • 0

    必须对字符串列表进行一点转换,它很简单,只需将数组放入一个函数,使得并返回一个新的数组来显示

    PLUNKR我的例子如下

    示例

    my-comp.component.ts

    items: any[] = ["item1","item2","item3","item4","item5","item6","item7","item8","item9"];
    
    buildArr(theArr: String[]): String[][]{
    
        var arrOfarr = [];
        for(var i = 0; i < theArr.length ; i+=4) {
            var row = [];
    
            for(var x = 0; x < 4; x++) {
              var value = theArr[i + x];
                if (!value) {
                    break;
                }
                row.push(value);
            }
            arrOfarr.push(row);
        }
         return arrOfarr;
    }
    

    my-comp.component.html

    <table id="myTable" class="table">
        <thead>
            <tr>
                 <th>Item1</th>
                 <th>Item2</th>
                 <th>Item3</th>
                 <th>Item4</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let row of buildArr(items)">
                <td *ngFor="let item of row">{{item}}</td>
            </tr>
        </tbody>
    </table>
    
  • 9

    您可以在字符串数组数组中转换字符串数组:

    this.rowList = [];
    var stringList = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3];
    var colCount = 4;
    for (var i = 0; i < stringList.length; i = i + 4) {
        var element = stringList[i];
        var row = [];
        while (row.length < colCount) {
            var value = stringList[i + row.length];
            if (!value) {
                break;
            }
            row.push(value);
        }
        this.rowList.push(row);
    }
    

    然后只使用两个ngFor:

    <table>
        <tbody>
            <tr *ngFor="let row of rowList">
                <td *ngFor="let col of row">{{col}}</td>
            </tr>
        </tbody>
    </table>
    
  • 2
    <table>
    <thead>
       <th>..</th>
    <th>..</th>
    <th>..</th>
    <th>..</th>
    </thead>
    <tbody>
    <tr ng-repeat="for component in components | groupBy: 3">
    Data here
    </tr>
    </tbody>
    </table>
    

    这将需要角度滤波器模块/库 . 我为Sorting elements in AngularJS for nested ng-repeat问题做了类似的事情 .

相关问题