【问题标题】:Generate colums w/ Angular Material using an *ngFor使用 *ngFor 生成带有/ Angular Material 的列
【发布时间】:2019-03-01 11:46:26
【问题描述】:

我正在使用从组件中获取数据的教程。

这里我必须自己插入每一列,而不是像页面底部的示例那样生成它们。

<div>
  <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Id </th>
      <td mat-cell *matCellDef="let user"> {{user.id}} </td>
    </ng-container>

    <ng-container matColumnDef="firstName">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
      <td mat-cell *matCellDef="let user"> {{user.firstName}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</div>

这里我没有使用 Material,我从一个字符串 [] 生成每一列:

getColumns(): string[] {
  return ['id', 'firstName', 'lastName', 'age'];
}//this is in my service

因此,如果我删除或修改服务中的列,它将在表中删除。

<table>
<tr>
  <th *ngFor="let col of columns" >{{col}}
  </th>
</tr>
<tr *ngFor="let user of users">
  <td *ngFor="let col of columns">{{user[col]}}</td>
</tr>
</table>
<div>
</div>

如何在 ng-container、th 和 td 中应用相同的方法?

【问题讨论】:

  • 您的问题没有解释您的预期输出,也没有解释您遇到的问题。请解释更多,或者您可以查看How to ask a good question ?
  • @GigaBite 我编辑了问题,希望现在更好,谢谢。

标签: html angular frontend ngfor


【解决方案1】:

你可以这样使用。

 <table class="table table-bordered table-info">
                                <thead class="bg-primary text-white">
                                    <tr>
                                        <th>Product</th>
                                        <th>Qty</th>
                                        <th>Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr *ngFor='let kotitems of cartitems'>
                                        <td>{{kotitems.Product}}</td>
                                        <td>{{kotitems.Qty}}</td>
                                        <td>{{kotitems.Amt}}</td>
                                    </tr>
                                </tbody>
                                <tfoot class="bg-primary text-white">
                                    <tr>
                                        <td>Total</td>
                                        <td colspan="2" style="text-align: center;">{{getSum()}}</td>
                                    </tr>
                                </tfoot>
                            </table>

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 2017-11-17
    • 2016-02-24
    • 2019-10-18
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多