Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 7: Link for whole row

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.

like image 287
Laess3r Avatar asked Dec 13 '18 14:12

Laess3r


People also ask

What is * MatHeaderCellDef?

MatHeaderCellDef extends CdkHeaderCellDef Header cell definition for the mat-table. Captures the template of a column's header cell and as well as cell-specific properties. Selector: [matHeaderCellDef]

What is multiTemplateDataRows?

multiTemplateDataRows have a different variable to hold the row's index called dataIndex . Access the row's index using let k = dataIndex . <!-- Row content--> <mat-row *matRowDef="let row; columns: displayedColumns; let k = dataIndex;" matRipple (click)="this.expandRow(row, k)"> </mat-row>


2 Answers

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

like image 168
M.Ortega Avatar answered Oct 12 '22 08:10

M.Ortega


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>
like image 24
andii1997 Avatar answered Oct 12 '22 09:10

andii1997