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.
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]
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>
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...
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With