javascript 如何在Angular mat-table中添加按钮?

x6yk4ghg  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(198)

我已经成功地使用了Angular mat-table来显示数据库中的数据:
enter image description here

<table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5">
            <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
                <th mat-header-cell *matHeaderCellDef>{{ getUserColumnDisplayName(column) }}</th>
                <td mat-cell *matCellDef="let emp">{{ emp[column] }}</td>
            </ng-container>
          
            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let emprow; columns: displayedColumns" (click)="onRowExchangeClicked(emprow)"
                [ngClass]="{ 'clicked-row': true  }"></tr>
        </table>

        <mat-paginator [length]="100" [pageSize]="10" [pageSizeOptions]="[5, 10, 25, 100, 200]"
            aria-label="Select page">
        </mat-paginator>

现在我想添加另一列,其中包含按钮。因此在component.ts中,我添加了一个名为actions的新列:

displayedColumns: string[] = ['firstName', 'lastName', 'email', ..., 'type','actions'];

在我的HTML中,我添加了这个容器:

<ng-container matColumnDef="actions">
                <mat-header-cell *matHeaderCellDef>actions</mat-header-cell>
                <mat-cell *matCellDef="let row">
                <button mat-button>Edit</button>
                </mat-cell>
            </ng-container>

但是当我运行这个项目时,我得到了这个错误:
enter image description here

iq3niunx

iq3niunx1#

您应该像这样将displayedColumns与colDefs分开

colDefs: string[] = ['firstName', 'lastName', 'email', ..., 'type']; // removed the 'actions';

displayedColumns: string[] = [...colDefs, 'actions', 'any additional columns ...'];

那么您的组件应该如下所示

<table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5">
            <ng-container [matColumnDef]="column" *ngFor="let column of colDefs">
                <th mat-header-cell *matHeaderCellDef>{{ getUserColumnDisplayName(column) }}</th>
                <td mat-cell *matCellDef="let emp">{{ emp[column] }}</td>
            </ng-container>
            <ng-container matColumnDef="actions">
                <mat-header-cell *matHeaderCellDef>actions</mat-header-cell>
                <mat-cell *matCellDef="let row">
                <button mat-button>Edit</button>
                </mat-cell>
            </ng-container>
          
            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let emprow; columns: displayedColumns" (click)="onRowExchangeClicked(emprow)"
                [ngClass]="{ 'clicked-row': true  }"></tr>
        </table>

        <mat-paginator [length]="100" [pageSize]="10" [pageSizeOptions]="[5, 10, 25, 100, 200]"
            aria-label="Select page">
        </mat-paginator>

相关问题