如何将值写入不同的单元格

时间:2016-09-29 19:33:21

标签: angular

我有这段代码

<table class="table table-bordered">
    <tr *ngFor="let el of elements">       
       <td>{{el.name}}</td><td></td><td></td>
    </tr>
 </table>

el对象上还有一个level属性。它是一种数字类型。我想根据el.level值将el.name值写入单元格。例如,如果级别值为1 =单元格1,则2 =单元格2,依此类推......

3 个答案:

答案 0 :(得分:1)

如果你没有多少关卡,你可以这样做:

<table class="table table-bordered">
    <tr *ngFor="let el of elements">       
        <td><span *ngIf="el.lvl == 1">{{el.name}}</span></td>
        <td><span *ngIf="el.lvl == 2">{{el.name}}</span></td>
        <td><span *ngIf="el.lvl == 3">{{el.name}}</span></td>
    </tr>
</table>

答案 1 :(得分:1)

让我们看看这样的事情是否有效 - 我没有测试过:

<table class="table table-bordered">
    <tr *ngFor="let el of elements" #thisRow (onload)=setChildContent(thisRow, el)>
        <td></td><td></td><td></td> // leave it empty!
    </tr>
</table>

然后在你的component.ts文件中你有这个功能

export class SmartAnswerComponent {

    // this function will be called for each row as soon as it loads

    setChildContent(thisRow, el){
        let childIndex = el.lvl // or whatever property gives you the index
        let parent = thisRow // dumb code but good for explaining

        parent[childIndex].innerText = el.name; // here you set the name in the cell you want -assuming that the cell was previously created.
    }
}

我看到你手动设置了3列。这是正常的 - 一个有3列的表 - 没什么特别的。

但是如果你想基于el.lvl动态地生成列数(单元格),那么你只需要创建一个将使用最大lvl的el的函数。如果我们有一个正常的引导程序表,这是预期的。每行的单元格数相同..

getTheNumberOfColumnsInThisTable(elements){
   let maxLvlNumber = elements.map(el => el.lvl) // here you get an array with only the levels.
   .reduce((previousValue, currentValue) => {
       if(previousValue < currentValue){
          return currentValue;
       }else{
          return previousValue;
       }
   }, 0 )
   let arrayWithMaxLvlNumberElements =  Array(maxLvlNumber).fill().map((x,i)=>i); // we can't iterate in *ngFor over a number like MaxLvlNumberElements,  so instead we create an array with that many elements.
   return arrayWithMaxLvlNumberElements;

}

然后使用此函数创建一个列的空列表,如下所示:

    // in your component.ts you do:
    this.numberOfColumns = getTheNumberOfColumnsInThisTable(this.elements)


    // in your component.html you do:
    <table class="table table-bordered">

       <tr *ngFor="let el of elements" #thisRow (onload)=setChildContent(thisRow, el)> // rows created.

       <td *ngFor="let oneColumn of numberOfColumns"></td> // cells created. -> don't do anything here. Leve them empty. the setChildContent() function will fill them.
        // of course this will give you the same number of cells(columns) on each row.
       </tr>
    </table>

如果您不想在每一行上使用相同数量的列,则可以更改单元格创建代码,如下所示:

<td *ngFor="let eachCell of el.lvl "></td> // el.lvl can't be a number so transformeit in array as above.

答案 2 :(得分:0)

不能以一种很好的方式做到这一点。你必须在el上创建额外的属性,它将是长度为el.level的数组,例如。

el.levels = Array(el.level).fill(someValue)

而不是模板

<td *ngFor="let l of levels; let isLast=last">{{(isLast) ? el.name: ''}}</td>