0
votes

I am new to angular & angular material. Please apologize if the question asked very trivial in nature.

I have been working on an application that has a component with an angular material data table.

The table has information that is fetched from a service.

My requirement is to have one of the records (the first in the data table) preselected by highlighting with a color in the angular material table and also render the information in that row in a form adjacent to the table in the same component.

If the user has selected any other row in the angular material data table, the form should reload the newly selected record information in the form

I have seen some examples that has checkbox, but I do not intend to have any multi-select operations on the records in the table.

An example of my requirement can be seen from the screenshot below

enter image description here

1
Are you sure data table is the best approach for this? Is it really necessary? Did you consider using List instead? material.angular.io/components/list/api - MoxxiManagarm
I was considering data table because the number of records rendered in this case could several hundreds or even thousands. Since Material table comes with pagination i thought it would be best to use a data table for this requirement. Also table would support sorting which could be another consideration for going with a table - svijay.aug12

1 Answers

0
votes

It's only add a variable in your .ts e.g. selectedIndex. Then in the part where you define the mat-row you can use some like

<tr mat-row *matRowDef="let row; columns: displayedColumns;let i = index"
     [style.background]="i==selectedIndex?'red':'inherit'"
     (click)="selectedIndex=i">
</tr>

In this case I only change the [style.background], you can use [ngClass]="{'yourClass':i==selectedIndex}" and define in your .css the class

At first, make that selectedIndex equal 0

See the example in stackblitz