29

我需要在Angular2中做同样的事情:

<?php
foreach ($somethings as $something) {
    foreach ($something->children as $child) {
        echo '<tr>...</tr>';
    }
}

这可以通过ngFor<table>实现,而不是在和之间添加新元素<tr>吗?

4

5 回答 5

24

我有一个样本可能与您想要的相似:

<table id="spreadsheet">
    <tr *ngFor="let row of visibleRows">
        <td class="row-number-column">{{row.rowIndex}}</td>
        <td *ngFor="let col of row.columns">
            <input  data-id="{{col.rowIndex}}-{{col.columnIndex}}" [value]="col.cellValue" (input)="col.cellValue = $event.target.value" (click)="model.selectColumn(col)" (keyup)="navigate($event)" />
        </td>
    </tr>
</table>

我用它来渲染一个看起来像网格的电子表格,如下所示:http ://www.syntaxsuccess.com/angular-2-samples/#/demo/spreadsheet

于 2016-02-06T14:59:06.293 回答
8

如果您需要 2 个或更多 foreach 循环来绘制表格行,则需要执行类似于以下操作。

<template ngFor let-rule [ngForOf]="model.rules" let-ruleIndex="index">
    <template ngFor let-clause [ngForOf]="rule.clauses" let-clauseIndex="index">
        <tr>
            <td>{{clause.name}}</td>
        </tr>
    </template>
</template>    
于 2016-09-28T10:07:46.630 回答
5

使用 ngFor 语法的“模板”形式,参见此处。它比更简单的*ngFor版本更冗长,但这是您在不输出 html 的情况下实现循环的方式(直到您打算这样做)。一个例外:您仍然会在您的内部获得 html 评论,<table>但我希望没关系。这是一个工作 plunkr:http ://plnkr.co/edit/KLJFEQlwelPJfNZYVHrO?p=preview

@Component({
  selector: 'my-app',
  providers: [],
  directives: [],
  template: `
  <table>
    <template ngFor #something [ngForOf]="somethings" #i="index">
      <template ngFor #child [ngForOf]="something.children" #j="index">
      <tr>{{child}}</tr>
      </template>
    </template>
  </table>
  `
})
export class App {
  private somethings: string[][] = [
    {children: ['foo1', 'bar1', 'baz1']},
    {children: ['foo2', 'bar2', 'baz2']},
    {children: ['foo3', 'bar3', 'baz3']},
  ]
}
于 2016-02-07T18:44:43.943 回答
3

模板对我不起作用,但带有 ngForOf 的 ng-template 可以解决问题:

<ng-template ngFor let-parent [ngForOf]="parent" >
    <tr *ngFor="let child of parent.children">
        <td>
            {{ child.field1 }}
        </td>
        <td> 
            {{ child.field2 }}
        </td>
        <td> ... and so one ... </td>
    </tr>
</ng-template>
于 2019-05-21T08:56:33.413 回答
0

我只是想为我的数据库中的任何表显示数据。我是这样做的:

我的 TypeScript Ajax 调用 table.component.ts 中的 API:

http.get<ITable>(url, params).subscribe(result => {
  this.tables = result;
}, error => console.error(error));

我的表

 interface ITable {
  tableName: string;
  tableColumns: Array<string>;
  tableDatas: Array<Array<any>>;
}

我的 table.component.html

<table class='table' *ngIf="tables">
  <thead>
    <tr>
      <th *ngFor="let tableColumn of tables.tableColumns">{{ tableColumn }}</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let tableData of tables.tableDatas">
      <td *ngFor="let data of tableData">{{ data }}</td>
    </tr>
  </tbody>
</table>
于 2018-05-31T11:53:22.453 回答