Highlight selected row in ngFor – Angular 2

October 26, 2016
by Inaam Hussain
  • highlight selected row angular2

In this Angular2 tutorial, we will see how to highlight selected row in a table using ngFor & ngClass directive.
First will display all the data in the table using ngFor directive. For that, we had already written a tutorial. Please refer below link for more details.

Also, If you are just getting started with Angular 2, here are a few tutorials and courses that can help you with the basics and setup.


What we are building?

highlight selected row demo

highlight selected row demo

In above demo, you can see that it’s highlighting with the blue color selected row based on clicked.

Getting Started

Let’s start with clone repository first. Using below command we can easily download code and start working on that,

git clone https://github.com/Inaamhusain/Highlight-selected-row-in-ngFor-Angular-2.git highlightSelectedRow

cd highlightSelectedRow

Using above command will get all the code related to highlightSelectedRow folder and the go to that folder and then to install dependencies run following command,

npm install

To start the application run following command,

npm start

After installing and running application you can see following screen,

highlight row selected app

highlight row selected app

ngFor & ngClass Directives

Let’s start with creating home component in which display list of games in table.

import {Component} from '@angular/core';
    selector: 'app-home',
    templateUrl: './app/home/home.component.html'
export class HomeComponent {
    headMessage : string;
    selectedRow : Number;
    setClickedRow : Function;
    games : [{
        game: string,
        platform : string,
        release : string
        this.headMessage = "Please click below rows !!";
        this.games = [{
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
            game : "Amplitude",
            platform: " PS4",
            release : "January 5"
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
            game : "Resident Evil Zero HD Remaster",
            platform: "Win, PS3, PS4, X360, XBO",
            release : "January 19"
            game : "Lego Marvel's Avengers",
            platform: "Win, X360, XBO, PS3, PS4, PSVita, WiiU, 3DS",
            release : "January 26"
        this.setClickedRow = function(index){
            this.selectedRow = index;

and HTML template for home component is as follow,


<table class="table table-hover">
            <th>Game Name</th>
            <th>Release Date</th>
        <tr *ngFor="let game of games; let i = index" (click)="setClickedRow(i)" [class.active]="i == selectedRow">

<div class="well well-lg">
    Selected Row : <strong>{{selectedRow}}</strong>

Start with home.component.ts. In which we have a list of game information which is going to display in the table. ( i.e : games (array of objects) ).
and one function setClickedRow, that will be called when we clicked on a row of the table which is going to set selected row index to the selectedRow variable.
Now will see the template for adding class active to selected row. So that it will highlight table row. Below is the small CSS code which we need to add in CSS file.

.table tr.active td {
  background-color:#123456 !important;
  color: white;

In home.component.html template will add a small piece of code for adding an active class with the ngFor directive.

<tr *ngFor="let game of games; let i = index" (click)="setClickedRow(i)" [class.active]="i == selectedRow">

In above code will use ngFor directive for looping through the data and display in the table. and then click event, when we click on a row it will set row index to the variable namely selectedRow. and for the set class to active will add following ngClass code to the element.
[class.active]="i == selectedRow"
So we have the condition here if i is equal to selectedRow then it will set an active class for that row.

For more detail information about ngClass you can visit it’s official documentation.

Now whenever you click on any row our function setClickedRow(i) will set the value of selectedRow to the index of the row clicked,thus the ngClass argument for that row will evaluate to true and the .active class will be applied for that row.


In this Angular2 tutorial, we have learned to use ngClass with ngFor directive to display data and highlight selected row in Angular 2 application.

More Angular 2 Stuff

  1. Angular 2 Official Documentation
  2. Learn Angular 2 From our Free Video Course on YouTube
  3. Learn Angular 2 by building 12 apps
  4. Angular 2 by Istvan Novak


Engineer. Blogger. I like to be updated on new upcoming emerging technologies.

Get notified on our new articles

Subscribe to get the latest on Node.js, Angular, Blockchain and more. We never spam!
First Name:


  1. |

    Thank you so much for this. The trick helped me. 🙂

  2. |

    the ng for is not working

    error is :
    Unhandled Promise rejection: Template parse errors:
    Can't bind to 'ngForOf' since it isn't a known property of 'tr'. ("
                    ]*ngFor="let game of games;"&gt;
                        {{g"): [email protected]:20
    Property binding ngForOf not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("
                    [ERROR -&gt;]
                        &lt;td&quot;): [email protected]:16 ; Zone:  ; Task: Promise.then ; Value: SyntaxError {__zone_symbol__error: Error: Template parse errors:
    Can't bind to 'ngForOf' since it isn't a known property of 'tr'. ("
      ……} Error: Template parse errors:
    Can't bind to 'ngForOf' since it isn't a known property of 'tr'. ("
                    ]*ngFor="let game of games;"&gt;
                        {{g"): [email protected]:20
    Property binding ngForOf not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("
                    [ERROR -&gt;]
                        &lt;td&quot;): [email protected]:16
        at SyntaxError.ZoneAwareError (http://localhost:3000/node_modules/zone.js/dist/zone.js:992:33)
        at SyntaxError.BaseError [as constructor] (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:1592:20)
        at new SyntaxError (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:1795:20)
        at TemplateParser.parse (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:11435:23)
        at JitCompiler._compileTemplate (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:27548:72)
        at eval (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:27431:66)
        at Set.forEach (native)
        at JitCompiler._compileComponents (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:27431:23)
        at createResult (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:27313:23)
        at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:334:26)
        at Zone.run (http://localhost:3000/node_modules/zone.js/dist/zone.js:126:43)
        at http://localhost:3000/node_modules/zone.js/dist/zone.js:713:57
        at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:367:31)
        at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:166:47)
        at drainMicroTaskQueue (http://localhost:3000/node_modules/zone.js/dist/zone.js:546:35)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:424:25)
    consoleError @ zone.js:522
    handleUnhandledRejection @ zone.js:527
    _loop_1 @ zone.js:562
    drainMicroTaskQueue @ zone.js:566
    ZoneTask.invoke @ zone.js:424
    zone.js:524 ZoneAwareError {__zone_symbol__error: Error: Uncaught (in promise): Error: Template parse errors:
    Can&#039;t bind to &#039;ngForOf&#039; since it isn&#039;t a……}
    consoleError @ zone.js:524
    handleUnhandledRejection @ zone.js:527
    _loop_1 @ zone.js:562
    drainMicroTaskQueue @ zone.js:566
    ZoneTask.invoke @ zone.js:424
    util.js:220 Google Maps API warning: InvalidKey https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key
    DB.j @ util.js:220
    (anonymous) @ js?key=YOUR_KEY:133
    (anonymous) @ js?key=YOUR_KEY:53
    (anonymous) @ js?key=YOUR_KEY:50
    (anonymous) @ js?key=YOUR_KEY:53
    (anonymous) @ js?key=YOUR_KEY:104
    (anonymous) @ js?key=YOUR_KEY:50
    (anonymous) @ js?key=YOUR_KEY:104
    (anonymous) @ js?key=YOUR_KEY:50
    (anonymous) @ js?key=YOUR_KEY:104
    Sc @ js?key=YOUR_KEY:52
    Rc.ib @ js?key=YOUR_KEY:104
    (anonymous) @ util.js:1
    js?key=YOUR_KEY:35 Google Maps API error: InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error
    • |

      hi bavna ,use *ngFor instead of *ngForOf

  3. |

    Thank you, this help me a lot.

  4. |

    Thanks, but it doesn’t deselect the others when i click on a row. when i click on 3 rows, they all are selected

  5. n


  6. |

    Worked great! Thanks!

  7. |

    i am getting an error “Member ‘setClickedRow’ is not callable”

  8. |

    Hi. In your table, you have 3 columns; Game name, Platform and Release Date. Is there a way to click on the selected row and tabulate another table with only the last 2 column(Platform and Release Date)?? Thanks

  9. |

    I’m using the same code, but to highlight an item when selected in the sidebar. But the selection goes away immediately. Could you help? Thanks

  10. |

    nice But i want to clear selected row when i clicked on outside how can i do that

  11. |

    Super helpful, thank you!

  12. code android example

    i want change backgroud color when click

  13. |

    how to sort table data using perticular id ??

Leave a Comment