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.










Join the conversation! Your thoughts help the community grow.