Angular 2-4 Mat-Table row in another component

Viewed 3407

I would like to know if I can place the mat table rows in another component different from the table component, here is an example:

<mat-table #table [dataSource]="dataSource" class="table" matSort>
<user-table-row> </user-table-row>

  <ng-container matColumnDef="profile">
    <mat-header-cell *matHeaderCellDef mat-sort-header class="header-cell"> Profile Type </mat-header-cell>
    <mat-cell *matCellDef="let user" class="cell"> {{user.profile.type}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="status">
    <mat-header-cell *matHeaderCellDef mat-sort-header class="header-cell"> Status </mat-header-cell>
    <mat-cell *matCellDef="let user" class="cell"> {{user.profile.status}} </mat-cell>
  </ng-container>


<!-- Header and Row Declarations -->
  <mat-header-row *matHeaderRowDef="['createdAt', 'email', 'profile', 'status', 'isApproved', 'actions']" class="header-row"></mat-header-row>
  <mat-row *matRowDef="let row; columns: ['createdAt', 'email', 'profile', 'status', 'isApproved', 'actions']" class="row"></mat-row>
</mat-table>

How do I make something like this:

<mat-table #table [dataSource]="dataSource" class="table" matSort>
  <user-table-row> </user-table-row>
</mat-table>

Is it possible, anyone have done this before?

2 Answers

Thanks so much for your solution Benjamin

Can you think of a better (more Angular like) solution for column-header?

This is what I came up with:

<my-table>
  <!-- rowColumn matches the displayedColumns array -->
  <ng-template rowColumn="foo" appColumnHeader="foo##MyCustomFooName" let-row>{{row.profile.type}}</ng-template>
  <ng-template rowColumn="bar" let-customRowName>{{row.profile.status}}</ng-template>
</my-table>

TableColmnHeaderDirective:

import { Directive, Input, OnInit } from '@angular/core';

@Directive({
  selector: 'ng-template[appColumnHeader]',
})
export class TableColumnHeaderDirective implements OnInit {
  @Input() appColumnHeader: string;
  public column: string;
  public header: string;

  constructor() {}

  ngOnInit() {
    const splitted = this.appColumnHeader.split('##');
    this.column = splitted[0];
    this.header = splitted[1];
  }
}

TableComponen:

...
ngAfterContentInit() {
        this.columnHeaders = ArrayHelper.toMap(
          this.columnHeaderDirectives.toArray(),
          (val: TableColumnHeaderDirective) => val.column
        );
      }
...

table.html

<mat-header-cell *matHeaderCellDef>
    {{columnHeaders.get(column)?.header}}
</mat-header-cell>
Related