9
votes

I'm using Angular Material 7 tables (mat-table). What I want to achieve is a link for a whole row in order to show a detail page.

The requirement is to show a real link which can be opened in a new tab, so the usual (click)-event does not work.

I achieved to add a link around the content of every mat-cell, but as I have a lot of columns this is not a good solution.

Is there a nice way to convert every mat-row to a link (href)?

Edit: I removed my example as correct answer was given below.

4

4 Answers

12
votes

Well, you can do the classic trick of an empty a tag over the whole row. Simply put the tag into just ONE of ng-containers and give it a custom css rule:

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

  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let element">
      {{element.name}}          
      <a fxFlexFill [routerLink]="'/maintenance/data/'+element.id" class="mat-row-link"></a>
    </mat-cell>
  </ng-container>

  <ng-container matColumnDef="lastname">
    <mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
    <mat-cell *matCellDef="let element">          
      {{element.lastname}}
    </mat-cell>
  </ng-container>

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

</mat-table>

Then on CSS:

.mat-row{        
    position: relative;
}

.mat-row-link{
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;             
}

Just remember that an empty a tag will make the job, but doesn't comply all the SEO standars...

18
votes

Add routerLink to mat-row

<mat-row *matRowDef="let row; columns: displayedColumns;" [routerLink]="'transaction/' + row.id" class="row-hover"></mat-row>

OR

You could add click event and custom css class to mat-row:

<mat-row *matRowDef="let row; columns: displayedColumns;"
(click)="navigateTo(row)" class="row-hover"></mat-row>

then in .ts file:

import { Router } from '@angular/router';
...
...
constructor(private router: Router) {}
...
navigateTo(row: any) {
  this.router.navigate(['/maintenance/data/'+row.id]);
} 

And add css class

.row-link:hover {
  background-color: rgba(0, 0, 0, .05);
  cursor: pointer;
}
0
votes

You could add the row like defined in the Anuglar Material Docs. That way you can add the [routerLink] to the entire row instead of individual cells.

0
votes

You can wrap the whole row in an a-tag and add the routerLink to that. With that solution you'll get the native link handling. I'm using the cdk-table but I guess that should also work for the angular material table.

My solution looks as follow:

<cdk-table [dataSource]="data">
    ...
    <a *cdkRowDef="let row; columns; columns" [routerLink]="['path', row.id]">
        <cdk-row></cdk-row>
    </a>
</cdk-table>