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.

ng new calendardemo 

Open this project in Visual Studio Code and install bootstrap by using following command.

npm install bootstrap --save

Now open styles.css file and add Bootstrap file reference. To add reference in styles.css file add this line.

@import '~bootstrap/dist/css/bootstrap.min.css'; 

Create a new service using the following command.

ng g s demo

Now open demo.service.ts file and add the following lines: 

import { Injectable } from '@angular/core';  
import {HttpClient} from '@angular/common/http';      
@Injectable({  
  providedIn: 'root'  
})  
export class DemoService {  
  
  constructor(private http:HttpClient) { }  
  
  getdata()  
  {  
    return this.http.get<any>('http://localhost:2345/Api/employee/DemoData');   
  }  
}

Now create a new component by using the following command.

ng g c demo

Now open demo.component.html file and add the following code:

<div class="row">      
    <div class="col-sm-12 btn btn-primary">      
        How to Highlight selected Row in ngFor onclick/onmouseover in Angular 9  
    </div>      
  </div>  
<table class="table table-hover">  
    <thead>  
        <tr>  
            <th>ID</th>  
            <th>Name</th>  
            <th>Age</th>  
            <th>Address</th>  
            <th>City</th>  
            <th>Salary</th>  
            <th>Department</th>  
        </tr>  
    </thead>  
    <tbody>  
        <tr *ngFor="let emp of Employee; let i = index" (click)="ClickedRow(i)" [class.active]="i == HighlightRow">  
            <td>{{emp.Id}}</td>  
            <td>{{emp.Name}}</td>  
            <td>{{emp.Age}}</td>  
            <td>{{emp.Address}}</td>  
            <td>{{emp.City}}</td>  
            <td>{{emp.Salary}}</td>  
            <td>{{emp.Department}}</td>  
        </tr>  
    </tbody>  
</table> 

Open demo.component.ts file and add the following lines.

import { Component, OnInit } from '@angular/core';  
import { DemoService } from "../demo.service";  
@Component({  
  selector: 'app-demo',  
  templateUrl: './demo.component.html',  
  styleUrls: ['./demo.component.css']  
})  
export class DemoComponent implements OnInit  {  
  HighlightRow : Number;  
  Employee : any;  
  ClickedRow:any;  
  constructor(private demoService:DemoService){  
    this.ClickedRow = function(index){  
      this.HighlightRow = index;  
  }  
  };  
  ngOnInit(): void {    
    this.showdata();    
  }  
  showdata()  
  {  
    this.demoService.getdata().subscribe((res: any) => {    
      this.Employee=res;     
      console.log(this.Employee);     
  })    
  }   
};  

Add the following class in styles.css file.

.table tr.active td {  
    background-color:#48da24 !important;  
    color: white;  
} 

Now Open app.module.ts file and add the following code. 

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { HttpClientModule } from '@angular/common/http';    
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { DemoComponent } from './demo/demo.component';  
@NgModule({  
  declarations: [  
    AppComponent,  
    DemoComponent,  
      
  ],  
  imports: [  
    BrowserModule,  
    AppRoutingModule,HttpClientModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
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".

CREATE TABLE [dbo].[DemoData](    
    [Id] [int] IDENTITY(1,1) NOT NULL,    
    [Name] [nvarchar](50) NULL,    
    [Age] [nvarchar](50) NULL,    
    [Address] [nvarchar](50) NULL,    
    [City] [nvarchar](50) NULL,    
    [Salary] [nvarchar](50) NULL,    
    [Department] [nvarchar](50) NULL,    
 CONSTRAINT [PK_DemoData] PRIMARY KEY CLUSTERED     
(    
    [Id] ASC    
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
) ON [PRIMARY]    
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.

using Employeemanger.Models;  

Now add a method to fetch data from the database.

[Route("DemoData")]  
[HttpGet]  
public object DemoData()  
{  
    return DB.DemoDatas.ToList();  
}

Complete employee controller code.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
using Employeemanger.Models
namespace Employeemanger.Controllers  
{  
    [RoutePrefix("api/employee")]  
    public class EmployeeController : ApiController  
    {  
        ContactManagerEntities2 DB = new ContactManagerEntities2();  
        [Route("DemoData")]  
        [HttpGet]  
        public object DemoData()  
        {  
            return DB.DemoDatas.ToList();  
        }            
    }  
}   

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.

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");              
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.


Similar Articles