P
P
prolina2020-09-07 22:02:04
Angular
prolina, 2020-09-07 22:02:04

Adding a custom column to an Angular Material table?

There are a lot of tables in my project and I want to make a shared component to draw the table. Most often, the columns for the table will correspond to the data received from the server, but it happens that you need to add a separate column for deleting and editing. How can this be done? I tried the following (but how then to pass the edit and delete buttons to the Actions column):

<fo-table [data]="data" [templateRef]="template" [displayedColumns]="displayedColumns">
    <ng-template #template>
      <button mat-icon-button color="warn">
        <mat-icon>delete</mat-icon>
      </button>
      <button mat-icon-button color="primary">
        <mat-icon>edit</mat-icon>
      </button>
    </ng-template>
  </fo-table>

public data;
  public displayedColumns;
  constructor(
    private readonly keywordService: KeywordService
  ) {
    this.keywordService.getKeywordsList()
      .subscribe(res => {
        this.data = res;
        this.displayedColumns = Object.keys(this.data[0]);
        this.displayedColumns = [ ...this.displayedColumns, 'Actions']
      })
  }


f-table:

<section class="d-flex justify-content-center align-items-center">
  <table mat-table [dataSource]="tableData" class="mat-elevation-z8">
    <ng-container *ngFor="let col of displayedColumns" [cdkColumnDef]="col">
      <mat-header-cell *cdkHeaderCellDef> {{col}} </mat-header-cell>
      <mat-cell *cdkCellDef="let row"> {{row[col]}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="Actions">
        <th mat-header-cell *matHeaderCellDef></th>
        <td mat-cell *matCellDef="let person">
          <ng-container *ngTemplateOutlet="templateRef"></ng-container>
        </td>
<!--			<mat-header-cell *matHeaderCellDef> Action </mat-header-cell>-->
<!--			<mat-cell *matCellDef>-->
<!--				<ng-template *ngTemplateOutlet="templateRef"></ng-template>-->
<!--			</mat-cell>-->
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </table>
</section>

  @Input() public tableData;
  @Input() public displayedColumns: string[];

  @Input() templateRef: TemplateRef<any>;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question