0

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

svijay.aug12
  • 531
  • 3
  • 13
  • 32
  • Are you sure data table is the best approach for this? Is it really necessary? Did you consider using List instead? https://material.angular.io/components/list/api – MoxxiManagarm Sep 02 '19 at 10:16
  • 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 Sep 02 '19 at 11:00

1 Answers1

0

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

Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • 1
    Hi Eliseo, I see that you have set the ngClass. But If have to capture the first row to load a form, how do i do that? I need to capture the data from the record pointed by the selectedIndex to load a form & this should happen by default for the first row in the table on component load and reload everytime user changes the selection. – svijay.aug12 Sep 02 '19 at 11:45