How To Set Background Color Of A Selected Row Based On Checking/Unchecking Checkbox In Angular 10

Introduction

 
In this article, we will learn how to set the background color of a selected row based on checking or unchecking a checkbox in an Angular 10 application.
 
Prerequisites
  • Basic Knowledge of Angular 2 or higher
  • Visual Studio 
  • Node and NPM installed
  • Bootstrap
  • WEB API
  • SQL Server Management Studio
Create an Angular project using the following command:
  1. ng new rangesliderdemo  
Open this project in Visual Studio Code and install bootstrap using the following command: 
  1. npm install bootstrap --save     
 Now open styles.css file and add Bootstrap file reference. To add a reference in a 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 employee  
Now open employee.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 EmployeeService {  
  7.   
  8.   constructor(private http:HttpClient) { }  
  9.   Getemployee()  
  10.   {  
  11.    return this.http.get('https://localhost:44357/api/Employee/Getemployee');  
  12.   }  
  13. }  
 Now create a new component using the following command:
  1. ng g c employee  
Now open employee.component.ts file and add the following code:
  1. import { Component, OnInit } from '@angular/core';  
  2. import { EmployeeService } from "../employee.service";  
  3. @Component({  
  4.   selector: 'app-employee',  
  5.   templateUrl: './employee.component.html',  
  6.   styleUrls: ['./employee.component.css']  
  7. })  
  8. export class EmployeeComponent implements OnInit {  
  9.   checkedList: any;  
  10.   masterSelected: boolean;  
  11.   changBackground: boolean[] = [];  
  12.   changbcolor: boolean;  
  13.   constructor(private employeeService:EmployeeService) { }  
  14.   emoloyyes:any;  
  15.   ngOnInit() {  
  16.     this.Getemployee();  
  17.   }  
  18. Getemployee()  
  19. {  
  20.   this.employeeService.Getemployee().subscribe(result =>{  
  21.     this.emoloyyes=result;  
  22. console.log(result)  
  23.   })  
  24. }  
  25. CheckedData() {  
  26.   this.checkedList = [];  
  27.   for (var i = 0; i < this.emoloyyes.length; i++) {  
  28.     if (this.emoloyyes[i]['selected'])  
  29.       this.checkedList.push({ ClientId: this.emoloyyes[i].Id });  
  30.   }   
  31.   this.checkedList = JSON.stringify(this.checkedList);  
  32.   
  33. }  
  34. isAllSelected() {  
  35.   this.masterSelected = this.emoloyyes.every(function (item: any) {  
  36.     return item.selected == true;  
  37.   })  
  38.   this.CheckedData();  
  39. }  
  40. checkUncheckAll() {  
  41.   for (var i = 0; i < this.emoloyyes.length; i++) {  
  42.     this.emoloyyes[i]['selected'] = this.masterSelected;  
  43.   }  
  44.   this.CheckedData();  
  45. }  
  46. showbackcolor(id, $event, index) {  
  47.   if ($event) {  
  48.     this.changBackground[index] = true  
  49.   } else {  
  50.     this.changBackground[index] = false;  
  51.     this.changbcolor = false;  
  52.   }  
  53. }  
  54. showBackgroundColor(count) {  
  55.   if (this.masterSelected == false) {  
  56.     for (let i = 0; i < count; i++) {  
  57.       this.changBackground[i] = false;  
  58.     }  
  59.   
  60.   }  
  61.   else {  
  62.     for (let i = 0; i < count; i++) {  
  63.       this.changBackground[i] = true;  
  64.     }  
  65.   }  
  66. }  
  67. }   
Open employee.component.html file and add the following lines:
  1. <div class="row" style="margin-top:10px;margin-bottom: 10px;">          
  2.     <div class="col-sm-12 btn btn-success">          
  3.         How to Set background color of selected row based on check/uncheck Checkbox in Angular 10   
  4.     </div>          
  5.   </div>   
  6. <table class="table">  
  7.     <thead class="thead-dark">  
  8.         <tr>  
  9.             <th><input type="checkbox" name="checkbox"  value="checkbox"  
  10.                 [(ngModel)]="masterSelected" (change)="checkUncheckAll();showBackgroundColor(emoloyyes.length)"></th>  
  11.             <th>ID</th>  
  12.             <th>Name</th>  
  13.             <th>Type</th>  
  14.             <th>City</th>  
  15.             <th>Salary</th>  
  16.         </tr>  
  17.     </thead>  
  18.     <tbody>  
  19.         <tr *ngFor="let emp of emoloyyes; let i=index;"  [ngClass]="(changBackground[i]?'data-selected': '')">  
  20.             <td><input type="checkbox" [(ngModel)]="emp.selected"  value="{{emp.Id}}" (change)="isAllSelected();showbackcolor(emp.Id,$event.target.checked,i)"></td>  
  21.             <td>{{ emp.Id }}</td>  
  22.             <td>{{ emp.Employee_Name }}</td>  
  23.             <td>{{ emp.EmployeeType }}</td>  
  24.             <td>{{ emp.City }}</td>  
  25.             <td>{{ emp.Salary }}</td>  
  26.   
  27.         </tr>  
  28.     </tbody>  
  29. </table>  
Open employee.component.css file and add the following css class:
  1. .data-selected {  
  2.     background-color: #DEEDF9;  
  3.   }  
  4.     
Now Open app.module.ts file and add the following code:
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { HttpClientModule } from '@angular/common/http'  
  4. import { AppComponent } from './app.component';  
  5. import { SliderdemoComponent } from './sliderdemo/sliderdemo.component';  
  6. import { EmployeeComponent } from './employee/employee.component';  
  7. import { FormsModule } from '@angular/forms';  
  8. @NgModule({  
  9.   declarations: [  
  10.     AppComponent,  
  11.     SliderdemoComponent,  
  12.     EmployeeComponent  
  13.   ],  
  14.   imports: [  
  15.     BrowserModule,HttpClientModule,FormsModule  
  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 "Employee", and in this database, create a table. Give that table a name like "employeedetails".
  1. CREATE TABLE [dbo].[Employeedetails](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Employee Name] [nchar](10) NULL,  
  4.     [EmployeeType] [nvarchar](50) NULL,  
  5.     [Age] [int] NULL,  
  6.     [City] [nchar](10) NULL,  
  7.     [Salary] [int] NULL,  
  8.  CONSTRAINT [PK_Employeedetails] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [Id] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]  
  12. ) ON [PRIMARY]  
  13. GO  
Create a Web API Project
 
Open Visual Studio and click on create a new project:
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
Now select the project and click on the Next button.
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Now select the project name and project location and click on the Create button.
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Choose Web API as the template:
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Select EF Designer from the database and click the "Next" button:
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Add the connection properties, select the database name on the next page, and click OK:
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button: 
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Our data model is created now.
 
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 checkselectdemo.Models;  
 Now, add a method to fetch data from the database
  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 checkselectdemo.Models;  
  8. namespace checkselectdemo.Controllers  
  9. {  
  10.     public class EmployeeController : ApiController  
  11.     {  
  12.         EmployeeEntities DB = new EmployeeEntities();  
  13.         [HttpGet]  
  14.         public object Getemployee()  
  15.         {  
  16.             return DB.Employeedetails.ToList();  
  17.         }  
  18.     }  
  19. }  
  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'
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 
Check the checkbox in header and check all check got select and background color of table is changed
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
Now click on any checkbox in the table and check when we check background color has changed:
 
How To Set Background Color Of Selected Row Based On Check/Uncheck Checkbox In Angular 10
 

Summary


In this article, we learned how to set the background color of a selected row based on checking or unchecking a checkbox in an Angular 10 application.

Similar Articles