How To Highlight Selected Row In ngFor In Angular 9

Introduction

 
In this article, we will learn how to highlight a selected row in ngFor in Angular.
 
Prerequisites
  • Basic Knowledge of Angular 2 or higher
  • Visual Studio Code
  • Visual studio and SQL Server Management studio
  • Node and NPM installed
  • Bootstrap
Create an Angular project by using the following command.
  1. ng new calendardemo    
Open this project in Visual Studio Code and install bootstrap by using following command.
  1. npm install bootstrap --save      
 Now open styles.css file and add Bootstrap file reference. To add reference in styles.css file add this line.
  1. @import '~bootstrap/dist/css/bootstrap.min.css';    
Create a new service using the following command.
  1. ng g s demo  
Now open demo.service.ts file and add the following lines: 
  1. import { Injectable } from '@angular/core';  
  2. import {HttpClient} from '@angular/common/http';      
  3. @Injectable({  
  4.   providedIn: 'root'  
  5. })  
  6. export class DemoService {  
  7.   
  8.   constructor(private http:HttpClient) { }  
  9.   
  10.   getdata()  
  11.   {  
  12.     return this.http.get<any>('http://localhost:2345/Api/employee/DemoData');   
  13.   }  
  14. }  
  Now create a new component by using the following command.
  1. ng g c demo  
Now open demo.component.html file and add the following code:
  1. <div class="row">      
  2.     <div class="col-sm-12 btn btn-primary">      
  3.         How to Highlight selected Row in ngFor onclick/onmouseover in Angular 9  
  4.     </div>      
  5.   </div>  
  6. <table class="table table-hover">  
  7.     <thead>  
  8.         <tr>  
  9.             <th>ID</th>  
  10.             <th>Name</th>  
  11.             <th>Age</th>  
  12.             <th>Address</th>  
  13.             <th>City</th>  
  14.             <th>Salary</th>  
  15.             <th>Department</th>  
  16.         </tr>  
  17.     </thead>  
  18.     <tbody>  
  19.         <tr *ngFor="let emp of Employee; let i = index" (click)="ClickedRow(i)" [class.active]="i == HighlightRow">  
  20.             <td>{{emp.Id}}</td>  
  21.             <td>{{emp.Name}}</td>  
  22.             <td>{{emp.Age}}</td>  
  23.             <td>{{emp.Address}}</td>  
  24.             <td>{{emp.City}}</td>  
  25.             <td>{{emp.Salary}}</td>  
  26.             <td>{{emp.Department}}</td>  
  27.         </tr>  
  28.     </tbody>  
  29. </table>  
 Open demo.component.ts file and add the following lines.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { DemoService } from "../demo.service";  
  3. @Component({  
  4.   selector: 'app-demo',  
  5.   templateUrl: './demo.component.html',  
  6.   styleUrls: ['./demo.component.css']  
  7. })  
  8. export class DemoComponent implements OnInit  {  
  9.   HighlightRow : Number;  
  10.   Employee : any;  
  11.   ClickedRow:any;  
  12.   constructor(private demoService:DemoService){  
  13.     this.ClickedRow = function(index){  
  14.       this.HighlightRow = index;  
  15.   }  
  16.   };  
  17.   ngOnInit(): void {    
  18.     this.showdata();    
  19.   }  
  20.   showdata()  
  21.   {  
  22.     this.demoService.getdata().subscribe((res: any) => {    
  23.       this.Employee=res;     
  24.       console.log(this.Employee);     
  25.   })    
  26.   }   
  27. };  
Add the following class in styles.css file.
  1. .table tr.active td {  
  2.     background-color:#48da24 !important;  
  3.     color: white;  
  4.   }   
Now Open app.module.ts file and add the following code. 
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';    
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6. import { DemoComponent } from './demo/demo.component';  
  7. @NgModule({  
  8.   declarations: [  
  9.     AppComponent,  
  10.     DemoComponent,  
  11.       
  12.   ],  
  13.   imports: [  
  14.     BrowserModule,  
  15.     AppRoutingModule,HttpClientModule  
  16.   ],  
  17.   providers: [],  
  18.   bootstrap: [AppComponent]  
  19. })  
  20. export class AppModule { }  

Create database and a table

 
Open SQL Server Management Studio, create a database named "contactmanager", and in this database, create a table. Give that table a name like "demodata".
  1. CREATE TABLE [dbo].[DemoData](    
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Name] [nvarchar](50) NULL,    
  4.     [Age] [nvarchar](50) NULL,    
  5.     [Address] [nvarchar](50) NULL,    
  6.     [City] [nvarchar](50) NULL,    
  7.     [Salary] [nvarchar](50) NULL,    
  8.     [Department] [nvarchar](50) NULL,    
  9.  CONSTRAINT [PK_DemoData] PRIMARY KEY CLUSTERED     
  10. (    
  11.     [Id] ASC    
  12. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]    
  13. ON [PRIMARY]    
  14. GO    
Open Visual Studio and create a new project.
 
 
Change the name to empploeemanager.
 
 
Choose the template as Web API.
 
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
 
 
Select EF Designer from the database and click the "Next" button.
 
 
Add the connection properties and select database name on the next page and click OK
 
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click OK
 
 
Now, our data model is successfully created.
 
Right-click on the Controllers folder and add a new controller. Name it as "Employee controller" and add the following namespace in the Employee controller.
  1. using Employeemanger.Models;  
Now add a method to fetch data from the database.
  1. [Route("DemoData")]  
  2.         [HttpGet]  
  3.         public object DemoData()  
  4.         {  
  5.             return DB.DemoDatas.ToList();  
  6.         }  
Complete employee controller code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using Employeemanger.Models;  
  8.   
  9.   
  10. namespace Employeemanger.Controllers  
  11. {  
  12.   
  13.     [RoutePrefix("api/employee")]  
  14.     public class EmployeeController : ApiController  
  15.     {  
  16.         ContactManagerEntities2 DB = new ContactManagerEntities2();  
  17.   
  18.         [Route("DemoData")]  
  19.         [HttpGet]  
  20.         public object DemoData()  
  21.         {  
  22.             return DB.DemoDatas.ToList();  
  23.         }  
  24.   
  25.           
  26. }  
  27. }   
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");              
  2. config.EnableCors(cors);   
Now, go to Visual Studio code and run the project by using the following command: 'npm start'
 

Summary


In this article, we learned how to highlight a selected row in ngFor.