Angular 4 Material table highlight a row












32















I'm looking for a good way to hightlight the whole a row in md-table.

Should I do directive or what?

Anyone can help me with this?



<div class="example-container mat-elevation-z8">
<md-table #table [dataSource]="dataSource">

<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->

<!-- ID Column -->
<ng-container cdkColumnDef="userId">
<md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
</ng-container>

<!-- Progress Column -->
<ng-container cdkColumnDef="progress">
<md-header-cell *cdkHeaderCellDef> Progress </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.progress}}% </md-cell>
</ng-container>

<!-- Name Column -->
<ng-container cdkColumnDef="userName">
<md-header-cell *cdkHeaderCellDef> Name </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.name}} </md-cell>
</ng-container>

<!-- Color Column -->
<ng-container cdkColumnDef="color">
<md-header-cell *cdkHeaderCellDef>Color</md-header-cell>
<md-cell *cdkCellDef="let row" [style.color]="row.color"> {{row.color}} </md-cell>
</ng-container>

<md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
<md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
</div>


Table from: https://material.angular.io/components/table/overview










share|improve this question



























    32















    I'm looking for a good way to hightlight the whole a row in md-table.

    Should I do directive or what?

    Anyone can help me with this?



    <div class="example-container mat-elevation-z8">
    <md-table #table [dataSource]="dataSource">

    <!--- Note that these columns can be defined in any order.
    The actual rendered columns are set as a property on the row definition" -->

    <!-- ID Column -->
    <ng-container cdkColumnDef="userId">
    <md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
    <md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
    </ng-container>

    <!-- Progress Column -->
    <ng-container cdkColumnDef="progress">
    <md-header-cell *cdkHeaderCellDef> Progress </md-header-cell>
    <md-cell *cdkCellDef="let row"> {{row.progress}}% </md-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container cdkColumnDef="userName">
    <md-header-cell *cdkHeaderCellDef> Name </md-header-cell>
    <md-cell *cdkCellDef="let row"> {{row.name}} </md-cell>
    </ng-container>

    <!-- Color Column -->
    <ng-container cdkColumnDef="color">
    <md-header-cell *cdkHeaderCellDef>Color</md-header-cell>
    <md-cell *cdkCellDef="let row" [style.color]="row.color"> {{row.color}} </md-cell>
    </ng-container>

    <md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
    <md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
    </md-table>
    </div>


    Table from: https://material.angular.io/components/table/overview










    share|improve this question

























      32












      32








      32


      9






      I'm looking for a good way to hightlight the whole a row in md-table.

      Should I do directive or what?

      Anyone can help me with this?



      <div class="example-container mat-elevation-z8">
      <md-table #table [dataSource]="dataSource">

      <!--- Note that these columns can be defined in any order.
      The actual rendered columns are set as a property on the row definition" -->

      <!-- ID Column -->
      <ng-container cdkColumnDef="userId">
      <md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
      <md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
      </ng-container>

      <!-- Progress Column -->
      <ng-container cdkColumnDef="progress">
      <md-header-cell *cdkHeaderCellDef> Progress </md-header-cell>
      <md-cell *cdkCellDef="let row"> {{row.progress}}% </md-cell>
      </ng-container>

      <!-- Name Column -->
      <ng-container cdkColumnDef="userName">
      <md-header-cell *cdkHeaderCellDef> Name </md-header-cell>
      <md-cell *cdkCellDef="let row"> {{row.name}} </md-cell>
      </ng-container>

      <!-- Color Column -->
      <ng-container cdkColumnDef="color">
      <md-header-cell *cdkHeaderCellDef>Color</md-header-cell>
      <md-cell *cdkCellDef="let row" [style.color]="row.color"> {{row.color}} </md-cell>
      </ng-container>

      <md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
      <md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
      </md-table>
      </div>


      Table from: https://material.angular.io/components/table/overview










      share|improve this question














      I'm looking for a good way to hightlight the whole a row in md-table.

      Should I do directive or what?

      Anyone can help me with this?



      <div class="example-container mat-elevation-z8">
      <md-table #table [dataSource]="dataSource">

      <!--- Note that these columns can be defined in any order.
      The actual rendered columns are set as a property on the row definition" -->

      <!-- ID Column -->
      <ng-container cdkColumnDef="userId">
      <md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
      <md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
      </ng-container>

      <!-- Progress Column -->
      <ng-container cdkColumnDef="progress">
      <md-header-cell *cdkHeaderCellDef> Progress </md-header-cell>
      <md-cell *cdkCellDef="let row"> {{row.progress}}% </md-cell>
      </ng-container>

      <!-- Name Column -->
      <ng-container cdkColumnDef="userName">
      <md-header-cell *cdkHeaderCellDef> Name </md-header-cell>
      <md-cell *cdkCellDef="let row"> {{row.name}} </md-cell>
      </ng-container>

      <!-- Color Column -->
      <ng-container cdkColumnDef="color">
      <md-header-cell *cdkHeaderCellDef>Color</md-header-cell>
      <md-cell *cdkCellDef="let row" [style.color]="row.color"> {{row.color}} </md-cell>
      </ng-container>

      <md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
      <md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
      </md-table>
      </div>


      Table from: https://material.angular.io/components/table/overview







      angular angular-material2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 31 '17 at 13:26









      Taison MorrisTaison Morris

      182129




      182129
























          5 Answers
          5






          active

          oldest

          votes


















          47














          Update for Newer Material Version (md --> mat):



          html:



          <!-- Add the highlight class in row definiton of md-table -->
          <!-- Add click event to pass the selected row index -->

          <mat-row *cdkRowDef="let row; columns: displayedColumns;"
          [ngClass]="{'highlight': selectedRowIndex == row.id}"
          (click)="highlight(row)">
          </mat-row>


          Original Answer:



          You can do it by using ngClass and a flag like selectedRowIndex. Whenever clicked row index is equal to selectedRowIndex, the class will be applied.



          Plunker demo



          html:



          <!-- Add the highlight class in row definiton of md-table -->
          <!-- Add click event to pass the selected row index -->

          <md-row *cdkRowDef="let row; columns: displayedColumns;"
          [ngClass]="{'highlight': selectedRowIndex == row.id}"
          (click)="highlight(row)">
          </md-row>


          css:



          .highlight{
          background: #42A948; /* green */
          }


          ts:



          selectedRowIndex: number = -1;

          highlight(row){
          this.selectedRowIndex = row.id;
          }





          share|improve this answer





















          • 1





            this doesn't work for the new setup md -> mat : material.angular.io/components/table/overview please update your post?

            – tatsu
            Feb 26 '18 at 12:53






          • 1





            consider updating your answer to follow @Simon_Weaver 's answer

            – tatsu
            Feb 26 '18 at 13:39











          • how can we make only last cell not clickable

            – amyogiji
            Jun 20 '18 at 8:45



















          25














          In the table overview examples page they explain the SelectionModel for handling selections - which incidentally also handles multi-selection.



          selection is a SelectionModel defined in your component. I couldn't find any actual documentation for this but the implementation is extremely simple.



          selection = new SelectionModel<CustomerSearchResult>(false, null);


          The first parameter is allowMultiSelect, so to allow multiple items to be selected at once set it to true. When false the selection model will deselect any existing values when you set a new value.



          Then add a click event to select() the row and create your own css class for when the row is selected.



             <mat-table>
          ...

          <mat-row *matRowDef="let row; columns: displayedColumns;"
          [ngClass]="{ 'selected': selection.isSelected(row)}"
          (click)="selection.select(row)"></mat-row>

          </mat-table>


          The css class I added is below (the sample doesn't mention styling yet) and then you just need to add to your css



          .mat-row {
          min-height: 65px;

          &.selected {
          background: #dddddd;
          }
          }


          If your background color is too dark you'll need to add styles yourself to invert the text color.



          To handle selection use the onChange event of selection.



              // selection changed
          this.selection.onChange.subscribe((a) =>
          {
          if (a.added[0]) // will be undefined if no selection
          {
          alert('You selected ' + a.added[0].fullName);
          }
          });


          Or alternatively the selected items are in this.selection.selected.



          I'm hoping mat-table gets improved for common cases like this and they don't just leave everything up to the developer. Things like keyboard events etc. would be nice to be handled automatically with respect to the selection model.






          share|improve this answer





















          • 1





            If anyone finds proper documentation for SelectionModel please add a link.

            – Simon_Weaver
            Jan 7 '18 at 21:12











          • The issue with was confirmed to be a bug github.com/angular/material2/pull/9287

            – Simon_Weaver
            Jan 8 '18 at 22:44






          • 4





            your's is the best answer. this question should be reviewed by community because the current marked answer isn't the best nor correct.

            – tatsu
            Feb 26 '18 at 13:39






          • 1





            For people using this technique to select a single item in a master-detail type view: I don't have time right now to add to this answer, but I strongly recommend looking into using the angular router and learning about child routes and outlets before using this technique too extensively in your application. I'm finding it much better to highlight a 'selected' row based on the current route than trying to mess with a separate selectionModel for master/detail situations. It works in a much more 'angular' way (eg. if you have unfinished data you can prevent navigation).

            – Simon_Weaver
            Mar 3 '18 at 0:07













          • you are the champion, great solution.

            – Brayan Loayza
            Nov 22 '18 at 21:56



















          4














          I did not have unique identifiers like id column in my table data but this worked for me (material 6):



          HTML



           <tr mat-row *matRowDef="let row; columns: displayedColumns" 
          (click)="selectedRow = row" [ngClass]="{ 'selected': row === selectedRow }">
          </tr>


          add variable to TS



          selectedRow;


          (S)CSS



          .selected {
          background-color: red;
          }


          If you want to do more things than just styling when selecting a row, replace (click)="selectedRow = row" with (click)="selectRow(row)" and add this function to your ts:



          selectRow(row) {
          this.selectedRow = row;
          // more stuff to do...
          }





          share|improve this answer































            3














            So, I ran into this issue as well. I'm using the newer 'mat-' instead of 'md-', but I'm GUESSING it will be about the same...



            <mat-row
            *matRowDef="let row; columns: myColumns; let entry"
            [ngClass]="{ 'my-class': entry.someVal }">
            </mat-row>


            I didn't find that anywhere, I just tried it and it happened to work out, so I hope that's right. The big thing was tagging 'let entry' to the end of the other matRowDef stuff. Sorry I'm so late to the party. Hopefully this does someone some good.






            share|improve this answer

































              1














              For material": "^7.0.3",



              use the css name in html, without the single quote, to highlight the row



               .mat-row.highlighted {
              background: lightblue;
              }


              <tr mat-row *matRowDef="let row; columns: displayedColumn;"
              [ngClass]="{highlighted: selectedRowIndex == row.id}" (click)="highlight(row)" >
              </tr>


              highlight(row){
              this.selectedRowIndex = row.id;
              }





              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45417248%2fangular-4-material-table-highlight-a-row%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                47














                Update for Newer Material Version (md --> mat):



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <mat-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </mat-row>


                Original Answer:



                You can do it by using ngClass and a flag like selectedRowIndex. Whenever clicked row index is equal to selectedRowIndex, the class will be applied.



                Plunker demo



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <md-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </md-row>


                css:



                .highlight{
                background: #42A948; /* green */
                }


                ts:



                selectedRowIndex: number = -1;

                highlight(row){
                this.selectedRowIndex = row.id;
                }





                share|improve this answer





















                • 1





                  this doesn't work for the new setup md -> mat : material.angular.io/components/table/overview please update your post?

                  – tatsu
                  Feb 26 '18 at 12:53






                • 1





                  consider updating your answer to follow @Simon_Weaver 's answer

                  – tatsu
                  Feb 26 '18 at 13:39











                • how can we make only last cell not clickable

                  – amyogiji
                  Jun 20 '18 at 8:45
















                47














                Update for Newer Material Version (md --> mat):



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <mat-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </mat-row>


                Original Answer:



                You can do it by using ngClass and a flag like selectedRowIndex. Whenever clicked row index is equal to selectedRowIndex, the class will be applied.



                Plunker demo



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <md-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </md-row>


                css:



                .highlight{
                background: #42A948; /* green */
                }


                ts:



                selectedRowIndex: number = -1;

                highlight(row){
                this.selectedRowIndex = row.id;
                }





                share|improve this answer





















                • 1





                  this doesn't work for the new setup md -> mat : material.angular.io/components/table/overview please update your post?

                  – tatsu
                  Feb 26 '18 at 12:53






                • 1





                  consider updating your answer to follow @Simon_Weaver 's answer

                  – tatsu
                  Feb 26 '18 at 13:39











                • how can we make only last cell not clickable

                  – amyogiji
                  Jun 20 '18 at 8:45














                47












                47








                47







                Update for Newer Material Version (md --> mat):



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <mat-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </mat-row>


                Original Answer:



                You can do it by using ngClass and a flag like selectedRowIndex. Whenever clicked row index is equal to selectedRowIndex, the class will be applied.



                Plunker demo



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <md-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </md-row>


                css:



                .highlight{
                background: #42A948; /* green */
                }


                ts:



                selectedRowIndex: number = -1;

                highlight(row){
                this.selectedRowIndex = row.id;
                }





                share|improve this answer















                Update for Newer Material Version (md --> mat):



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <mat-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </mat-row>


                Original Answer:



                You can do it by using ngClass and a flag like selectedRowIndex. Whenever clicked row index is equal to selectedRowIndex, the class will be applied.



                Plunker demo



                html:



                <!-- Add the highlight class in row definiton of md-table -->
                <!-- Add click event to pass the selected row index -->

                <md-row *cdkRowDef="let row; columns: displayedColumns;"
                [ngClass]="{'highlight': selectedRowIndex == row.id}"
                (click)="highlight(row)">
                </md-row>


                css:



                .highlight{
                background: #42A948; /* green */
                }


                ts:



                selectedRowIndex: number = -1;

                highlight(row){
                this.selectedRowIndex = row.id;
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Apr 24 '18 at 2:13

























                answered Jul 31 '17 at 13:37









                NehalNehal

                7,70722039




                7,70722039








                • 1





                  this doesn't work for the new setup md -> mat : material.angular.io/components/table/overview please update your post?

                  – tatsu
                  Feb 26 '18 at 12:53






                • 1





                  consider updating your answer to follow @Simon_Weaver 's answer

                  – tatsu
                  Feb 26 '18 at 13:39











                • how can we make only last cell not clickable

                  – amyogiji
                  Jun 20 '18 at 8:45














                • 1





                  this doesn't work for the new setup md -> mat : material.angular.io/components/table/overview please update your post?

                  – tatsu
                  Feb 26 '18 at 12:53






                • 1





                  consider updating your answer to follow @Simon_Weaver 's answer

                  – tatsu
                  Feb 26 '18 at 13:39











                • how can we make only last cell not clickable

                  – amyogiji
                  Jun 20 '18 at 8:45








                1




                1





                this doesn't work for the new setup md -> mat : material.angular.io/components/table/overview please update your post?

                – tatsu
                Feb 26 '18 at 12:53





                this doesn't work for the new setup md -> mat : material.angular.io/components/table/overview please update your post?

                – tatsu
                Feb 26 '18 at 12:53




                1




                1





                consider updating your answer to follow @Simon_Weaver 's answer

                – tatsu
                Feb 26 '18 at 13:39





                consider updating your answer to follow @Simon_Weaver 's answer

                – tatsu
                Feb 26 '18 at 13:39













                how can we make only last cell not clickable

                – amyogiji
                Jun 20 '18 at 8:45





                how can we make only last cell not clickable

                – amyogiji
                Jun 20 '18 at 8:45













                25














                In the table overview examples page they explain the SelectionModel for handling selections - which incidentally also handles multi-selection.



                selection is a SelectionModel defined in your component. I couldn't find any actual documentation for this but the implementation is extremely simple.



                selection = new SelectionModel<CustomerSearchResult>(false, null);


                The first parameter is allowMultiSelect, so to allow multiple items to be selected at once set it to true. When false the selection model will deselect any existing values when you set a new value.



                Then add a click event to select() the row and create your own css class for when the row is selected.



                   <mat-table>
                ...

                <mat-row *matRowDef="let row; columns: displayedColumns;"
                [ngClass]="{ 'selected': selection.isSelected(row)}"
                (click)="selection.select(row)"></mat-row>

                </mat-table>


                The css class I added is below (the sample doesn't mention styling yet) and then you just need to add to your css



                .mat-row {
                min-height: 65px;

                &.selected {
                background: #dddddd;
                }
                }


                If your background color is too dark you'll need to add styles yourself to invert the text color.



                To handle selection use the onChange event of selection.



                    // selection changed
                this.selection.onChange.subscribe((a) =>
                {
                if (a.added[0]) // will be undefined if no selection
                {
                alert('You selected ' + a.added[0].fullName);
                }
                });


                Or alternatively the selected items are in this.selection.selected.



                I'm hoping mat-table gets improved for common cases like this and they don't just leave everything up to the developer. Things like keyboard events etc. would be nice to be handled automatically with respect to the selection model.






                share|improve this answer





















                • 1





                  If anyone finds proper documentation for SelectionModel please add a link.

                  – Simon_Weaver
                  Jan 7 '18 at 21:12











                • The issue with was confirmed to be a bug github.com/angular/material2/pull/9287

                  – Simon_Weaver
                  Jan 8 '18 at 22:44






                • 4





                  your's is the best answer. this question should be reviewed by community because the current marked answer isn't the best nor correct.

                  – tatsu
                  Feb 26 '18 at 13:39






                • 1





                  For people using this technique to select a single item in a master-detail type view: I don't have time right now to add to this answer, but I strongly recommend looking into using the angular router and learning about child routes and outlets before using this technique too extensively in your application. I'm finding it much better to highlight a 'selected' row based on the current route than trying to mess with a separate selectionModel for master/detail situations. It works in a much more 'angular' way (eg. if you have unfinished data you can prevent navigation).

                  – Simon_Weaver
                  Mar 3 '18 at 0:07













                • you are the champion, great solution.

                  – Brayan Loayza
                  Nov 22 '18 at 21:56
















                25














                In the table overview examples page they explain the SelectionModel for handling selections - which incidentally also handles multi-selection.



                selection is a SelectionModel defined in your component. I couldn't find any actual documentation for this but the implementation is extremely simple.



                selection = new SelectionModel<CustomerSearchResult>(false, null);


                The first parameter is allowMultiSelect, so to allow multiple items to be selected at once set it to true. When false the selection model will deselect any existing values when you set a new value.



                Then add a click event to select() the row and create your own css class for when the row is selected.



                   <mat-table>
                ...

                <mat-row *matRowDef="let row; columns: displayedColumns;"
                [ngClass]="{ 'selected': selection.isSelected(row)}"
                (click)="selection.select(row)"></mat-row>

                </mat-table>


                The css class I added is below (the sample doesn't mention styling yet) and then you just need to add to your css



                .mat-row {
                min-height: 65px;

                &.selected {
                background: #dddddd;
                }
                }


                If your background color is too dark you'll need to add styles yourself to invert the text color.



                To handle selection use the onChange event of selection.



                    // selection changed
                this.selection.onChange.subscribe((a) =>
                {
                if (a.added[0]) // will be undefined if no selection
                {
                alert('You selected ' + a.added[0].fullName);
                }
                });


                Or alternatively the selected items are in this.selection.selected.



                I'm hoping mat-table gets improved for common cases like this and they don't just leave everything up to the developer. Things like keyboard events etc. would be nice to be handled automatically with respect to the selection model.






                share|improve this answer





















                • 1





                  If anyone finds proper documentation for SelectionModel please add a link.

                  – Simon_Weaver
                  Jan 7 '18 at 21:12











                • The issue with was confirmed to be a bug github.com/angular/material2/pull/9287

                  – Simon_Weaver
                  Jan 8 '18 at 22:44






                • 4





                  your's is the best answer. this question should be reviewed by community because the current marked answer isn't the best nor correct.

                  – tatsu
                  Feb 26 '18 at 13:39






                • 1





                  For people using this technique to select a single item in a master-detail type view: I don't have time right now to add to this answer, but I strongly recommend looking into using the angular router and learning about child routes and outlets before using this technique too extensively in your application. I'm finding it much better to highlight a 'selected' row based on the current route than trying to mess with a separate selectionModel for master/detail situations. It works in a much more 'angular' way (eg. if you have unfinished data you can prevent navigation).

                  – Simon_Weaver
                  Mar 3 '18 at 0:07













                • you are the champion, great solution.

                  – Brayan Loayza
                  Nov 22 '18 at 21:56














                25












                25








                25







                In the table overview examples page they explain the SelectionModel for handling selections - which incidentally also handles multi-selection.



                selection is a SelectionModel defined in your component. I couldn't find any actual documentation for this but the implementation is extremely simple.



                selection = new SelectionModel<CustomerSearchResult>(false, null);


                The first parameter is allowMultiSelect, so to allow multiple items to be selected at once set it to true. When false the selection model will deselect any existing values when you set a new value.



                Then add a click event to select() the row and create your own css class for when the row is selected.



                   <mat-table>
                ...

                <mat-row *matRowDef="let row; columns: displayedColumns;"
                [ngClass]="{ 'selected': selection.isSelected(row)}"
                (click)="selection.select(row)"></mat-row>

                </mat-table>


                The css class I added is below (the sample doesn't mention styling yet) and then you just need to add to your css



                .mat-row {
                min-height: 65px;

                &.selected {
                background: #dddddd;
                }
                }


                If your background color is too dark you'll need to add styles yourself to invert the text color.



                To handle selection use the onChange event of selection.



                    // selection changed
                this.selection.onChange.subscribe((a) =>
                {
                if (a.added[0]) // will be undefined if no selection
                {
                alert('You selected ' + a.added[0].fullName);
                }
                });


                Or alternatively the selected items are in this.selection.selected.



                I'm hoping mat-table gets improved for common cases like this and they don't just leave everything up to the developer. Things like keyboard events etc. would be nice to be handled automatically with respect to the selection model.






                share|improve this answer















                In the table overview examples page they explain the SelectionModel for handling selections - which incidentally also handles multi-selection.



                selection is a SelectionModel defined in your component. I couldn't find any actual documentation for this but the implementation is extremely simple.



                selection = new SelectionModel<CustomerSearchResult>(false, null);


                The first parameter is allowMultiSelect, so to allow multiple items to be selected at once set it to true. When false the selection model will deselect any existing values when you set a new value.



                Then add a click event to select() the row and create your own css class for when the row is selected.



                   <mat-table>
                ...

                <mat-row *matRowDef="let row; columns: displayedColumns;"
                [ngClass]="{ 'selected': selection.isSelected(row)}"
                (click)="selection.select(row)"></mat-row>

                </mat-table>


                The css class I added is below (the sample doesn't mention styling yet) and then you just need to add to your css



                .mat-row {
                min-height: 65px;

                &.selected {
                background: #dddddd;
                }
                }


                If your background color is too dark you'll need to add styles yourself to invert the text color.



                To handle selection use the onChange event of selection.



                    // selection changed
                this.selection.onChange.subscribe((a) =>
                {
                if (a.added[0]) // will be undefined if no selection
                {
                alert('You selected ' + a.added[0].fullName);
                }
                });


                Or alternatively the selected items are in this.selection.selected.



                I'm hoping mat-table gets improved for common cases like this and they don't just leave everything up to the developer. Things like keyboard events etc. would be nice to be handled automatically with respect to the selection model.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Feb 17 at 2:01

























                answered Jan 7 '18 at 21:10









                Simon_WeaverSimon_Weaver

                72.8k62449523




                72.8k62449523








                • 1





                  If anyone finds proper documentation for SelectionModel please add a link.

                  – Simon_Weaver
                  Jan 7 '18 at 21:12











                • The issue with was confirmed to be a bug github.com/angular/material2/pull/9287

                  – Simon_Weaver
                  Jan 8 '18 at 22:44






                • 4





                  your's is the best answer. this question should be reviewed by community because the current marked answer isn't the best nor correct.

                  – tatsu
                  Feb 26 '18 at 13:39






                • 1





                  For people using this technique to select a single item in a master-detail type view: I don't have time right now to add to this answer, but I strongly recommend looking into using the angular router and learning about child routes and outlets before using this technique too extensively in your application. I'm finding it much better to highlight a 'selected' row based on the current route than trying to mess with a separate selectionModel for master/detail situations. It works in a much more 'angular' way (eg. if you have unfinished data you can prevent navigation).

                  – Simon_Weaver
                  Mar 3 '18 at 0:07













                • you are the champion, great solution.

                  – Brayan Loayza
                  Nov 22 '18 at 21:56














                • 1





                  If anyone finds proper documentation for SelectionModel please add a link.

                  – Simon_Weaver
                  Jan 7 '18 at 21:12











                • The issue with was confirmed to be a bug github.com/angular/material2/pull/9287

                  – Simon_Weaver
                  Jan 8 '18 at 22:44






                • 4





                  your's is the best answer. this question should be reviewed by community because the current marked answer isn't the best nor correct.

                  – tatsu
                  Feb 26 '18 at 13:39






                • 1





                  For people using this technique to select a single item in a master-detail type view: I don't have time right now to add to this answer, but I strongly recommend looking into using the angular router and learning about child routes and outlets before using this technique too extensively in your application. I'm finding it much better to highlight a 'selected' row based on the current route than trying to mess with a separate selectionModel for master/detail situations. It works in a much more 'angular' way (eg. if you have unfinished data you can prevent navigation).

                  – Simon_Weaver
                  Mar 3 '18 at 0:07













                • you are the champion, great solution.

                  – Brayan Loayza
                  Nov 22 '18 at 21:56








                1




                1





                If anyone finds proper documentation for SelectionModel please add a link.

                – Simon_Weaver
                Jan 7 '18 at 21:12





                If anyone finds proper documentation for SelectionModel please add a link.

                – Simon_Weaver
                Jan 7 '18 at 21:12













                The issue with was confirmed to be a bug github.com/angular/material2/pull/9287

                – Simon_Weaver
                Jan 8 '18 at 22:44





                The issue with was confirmed to be a bug github.com/angular/material2/pull/9287

                – Simon_Weaver
                Jan 8 '18 at 22:44




                4




                4





                your's is the best answer. this question should be reviewed by community because the current marked answer isn't the best nor correct.

                – tatsu
                Feb 26 '18 at 13:39





                your's is the best answer. this question should be reviewed by community because the current marked answer isn't the best nor correct.

                – tatsu
                Feb 26 '18 at 13:39




                1




                1





                For people using this technique to select a single item in a master-detail type view: I don't have time right now to add to this answer, but I strongly recommend looking into using the angular router and learning about child routes and outlets before using this technique too extensively in your application. I'm finding it much better to highlight a 'selected' row based on the current route than trying to mess with a separate selectionModel for master/detail situations. It works in a much more 'angular' way (eg. if you have unfinished data you can prevent navigation).

                – Simon_Weaver
                Mar 3 '18 at 0:07







                For people using this technique to select a single item in a master-detail type view: I don't have time right now to add to this answer, but I strongly recommend looking into using the angular router and learning about child routes and outlets before using this technique too extensively in your application. I'm finding it much better to highlight a 'selected' row based on the current route than trying to mess with a separate selectionModel for master/detail situations. It works in a much more 'angular' way (eg. if you have unfinished data you can prevent navigation).

                – Simon_Weaver
                Mar 3 '18 at 0:07















                you are the champion, great solution.

                – Brayan Loayza
                Nov 22 '18 at 21:56





                you are the champion, great solution.

                – Brayan Loayza
                Nov 22 '18 at 21:56











                4














                I did not have unique identifiers like id column in my table data but this worked for me (material 6):



                HTML



                 <tr mat-row *matRowDef="let row; columns: displayedColumns" 
                (click)="selectedRow = row" [ngClass]="{ 'selected': row === selectedRow }">
                </tr>


                add variable to TS



                selectedRow;


                (S)CSS



                .selected {
                background-color: red;
                }


                If you want to do more things than just styling when selecting a row, replace (click)="selectedRow = row" with (click)="selectRow(row)" and add this function to your ts:



                selectRow(row) {
                this.selectedRow = row;
                // more stuff to do...
                }





                share|improve this answer




























                  4














                  I did not have unique identifiers like id column in my table data but this worked for me (material 6):



                  HTML



                   <tr mat-row *matRowDef="let row; columns: displayedColumns" 
                  (click)="selectedRow = row" [ngClass]="{ 'selected': row === selectedRow }">
                  </tr>


                  add variable to TS



                  selectedRow;


                  (S)CSS



                  .selected {
                  background-color: red;
                  }


                  If you want to do more things than just styling when selecting a row, replace (click)="selectedRow = row" with (click)="selectRow(row)" and add this function to your ts:



                  selectRow(row) {
                  this.selectedRow = row;
                  // more stuff to do...
                  }





                  share|improve this answer


























                    4












                    4








                    4







                    I did not have unique identifiers like id column in my table data but this worked for me (material 6):



                    HTML



                     <tr mat-row *matRowDef="let row; columns: displayedColumns" 
                    (click)="selectedRow = row" [ngClass]="{ 'selected': row === selectedRow }">
                    </tr>


                    add variable to TS



                    selectedRow;


                    (S)CSS



                    .selected {
                    background-color: red;
                    }


                    If you want to do more things than just styling when selecting a row, replace (click)="selectedRow = row" with (click)="selectRow(row)" and add this function to your ts:



                    selectRow(row) {
                    this.selectedRow = row;
                    // more stuff to do...
                    }





                    share|improve this answer













                    I did not have unique identifiers like id column in my table data but this worked for me (material 6):



                    HTML



                     <tr mat-row *matRowDef="let row; columns: displayedColumns" 
                    (click)="selectedRow = row" [ngClass]="{ 'selected': row === selectedRow }">
                    </tr>


                    add variable to TS



                    selectedRow;


                    (S)CSS



                    .selected {
                    background-color: red;
                    }


                    If you want to do more things than just styling when selecting a row, replace (click)="selectedRow = row" with (click)="selectRow(row)" and add this function to your ts:



                    selectRow(row) {
                    this.selectedRow = row;
                    // more stuff to do...
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Aug 11 '18 at 10:43









                    ZuzzeZuzze

                    413




                    413























                        3














                        So, I ran into this issue as well. I'm using the newer 'mat-' instead of 'md-', but I'm GUESSING it will be about the same...



                        <mat-row
                        *matRowDef="let row; columns: myColumns; let entry"
                        [ngClass]="{ 'my-class': entry.someVal }">
                        </mat-row>


                        I didn't find that anywhere, I just tried it and it happened to work out, so I hope that's right. The big thing was tagging 'let entry' to the end of the other matRowDef stuff. Sorry I'm so late to the party. Hopefully this does someone some good.






                        share|improve this answer






























                          3














                          So, I ran into this issue as well. I'm using the newer 'mat-' instead of 'md-', but I'm GUESSING it will be about the same...



                          <mat-row
                          *matRowDef="let row; columns: myColumns; let entry"
                          [ngClass]="{ 'my-class': entry.someVal }">
                          </mat-row>


                          I didn't find that anywhere, I just tried it and it happened to work out, so I hope that's right. The big thing was tagging 'let entry' to the end of the other matRowDef stuff. Sorry I'm so late to the party. Hopefully this does someone some good.






                          share|improve this answer




























                            3












                            3








                            3







                            So, I ran into this issue as well. I'm using the newer 'mat-' instead of 'md-', but I'm GUESSING it will be about the same...



                            <mat-row
                            *matRowDef="let row; columns: myColumns; let entry"
                            [ngClass]="{ 'my-class': entry.someVal }">
                            </mat-row>


                            I didn't find that anywhere, I just tried it and it happened to work out, so I hope that's right. The big thing was tagging 'let entry' to the end of the other matRowDef stuff. Sorry I'm so late to the party. Hopefully this does someone some good.






                            share|improve this answer















                            So, I ran into this issue as well. I'm using the newer 'mat-' instead of 'md-', but I'm GUESSING it will be about the same...



                            <mat-row
                            *matRowDef="let row; columns: myColumns; let entry"
                            [ngClass]="{ 'my-class': entry.someVal }">
                            </mat-row>


                            I didn't find that anywhere, I just tried it and it happened to work out, so I hope that's right. The big thing was tagging 'let entry' to the end of the other matRowDef stuff. Sorry I'm so late to the party. Hopefully this does someone some good.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jan 4 '18 at 20:37

























                            answered Jan 4 '18 at 19:54









                            Nick LandkamerNick Landkamer

                            312




                            312























                                1














                                For material": "^7.0.3",



                                use the css name in html, without the single quote, to highlight the row



                                 .mat-row.highlighted {
                                background: lightblue;
                                }


                                <tr mat-row *matRowDef="let row; columns: displayedColumn;"
                                [ngClass]="{highlighted: selectedRowIndex == row.id}" (click)="highlight(row)" >
                                </tr>


                                highlight(row){
                                this.selectedRowIndex = row.id;
                                }





                                share|improve this answer




























                                  1














                                  For material": "^7.0.3",



                                  use the css name in html, without the single quote, to highlight the row



                                   .mat-row.highlighted {
                                  background: lightblue;
                                  }


                                  <tr mat-row *matRowDef="let row; columns: displayedColumn;"
                                  [ngClass]="{highlighted: selectedRowIndex == row.id}" (click)="highlight(row)" >
                                  </tr>


                                  highlight(row){
                                  this.selectedRowIndex = row.id;
                                  }





                                  share|improve this answer


























                                    1












                                    1








                                    1







                                    For material": "^7.0.3",



                                    use the css name in html, without the single quote, to highlight the row



                                     .mat-row.highlighted {
                                    background: lightblue;
                                    }


                                    <tr mat-row *matRowDef="let row; columns: displayedColumn;"
                                    [ngClass]="{highlighted: selectedRowIndex == row.id}" (click)="highlight(row)" >
                                    </tr>


                                    highlight(row){
                                    this.selectedRowIndex = row.id;
                                    }





                                    share|improve this answer













                                    For material": "^7.0.3",



                                    use the css name in html, without the single quote, to highlight the row



                                     .mat-row.highlighted {
                                    background: lightblue;
                                    }


                                    <tr mat-row *matRowDef="let row; columns: displayedColumn;"
                                    [ngClass]="{highlighted: selectedRowIndex == row.id}" (click)="highlight(row)" >
                                    </tr>


                                    highlight(row){
                                    this.selectedRowIndex = row.id;
                                    }






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 13 '18 at 9:21









                                    PriyaPriya

                                    112




                                    112






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45417248%2fangular-4-material-table-highlight-a-row%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Ottavio Pratesi

                                        Tricia Helfer

                                        15 giugno