Генерируйте столбцы с угловым материалом, используя * ngFor - PullRequest
0 голосов
/ 01 марта 2019

Я использую учебник, который берет данные из компонента.

Здесь я должен вставить каждый столбец самостоятельно, вместо этого я хочу сгенерировать их, как в примере внизу страницы.

<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, th и td?

1 Ответ

0 голосов
/ 01 марта 2019

Вы можете использовать как это.

 <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>
...