CheckBox Example In Angular 8 Using Web API And SQL Server

In this article, I'm going to perform an operation with checkbox in Angular 8 using Web API and SQL Server.

In this example, we will bind all locations and after that, we will add a company name with its branches. We will also create a server-side Web API. An Angular 8 built front-end will consume that API. Let's perform this step by step.
 
You can read my previous articles related to Angular 7 from the following links.
Prerequisites
  1. Visual Studio
  2. SQL Server
  3. js version > 10
  4. AngularCLI v8.0.3
  5. Visual studio code
  6. Bootstrap
Step 1:  Create a database and table
 
Create a database. Open SQL Server and create a new database and table. As you can see from the following query, I have created a database table called Branch Details and Company Details.
 
Branch Details
  1. CREATE TABLE [dbo].[BranchDetails](  
  2.     [BranchId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [BranchName] [varchar](100) NULL,  
  4.  CONSTRAINT [PK_BranchDetails] PRIMARY KEY CLUSTERED   
  5. (  
  6.     [BranchId] ASC  
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  8. ON [PRIMARY]  
  9.   
  10. GO  
  11.   
  12. SET ANSI_PADDING OFF  
  13. GO  
Company Details
  1. CREATE TABLE [dbo].[CompanyDetails](  
  2.     [CompnayID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [BranchName] [nvarchar](maxNULL,  
  4.     [CompanyName] [varchar](100) NULL,  
  5.  CONSTRAINT [PK_CompanyDetails] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [CompnayID] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  10.   
  11. GO  
  12.   
  13. SET ANSI_PADDING OFF  
  14. GO  
Note
You can choose the size of the column according to your requirement.
 
Step 2: Create a Web API Project

Now, we will create a Web API with the functionality of binding records from the database. Go to Visual Studio >> File >> New >> Project, and select Web Application. After that, click OK and you will see the templates. Select the Web API template.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Click OK
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Click OK.
 
Step 3:  Add ADO.NET Entity Data Model
 
Now, select Models folder >> Right click >>Add >> New Item >> select Data in left panel >>ADO.NET Entity Data Model.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Click the "Add" button.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Click "Next".
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Give the SQL server name and its credentials. Then, select the database and test connection. Click OK. 
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Click "Next".
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Select tables and click "Finish".
 
Step 4: Add API controller logic
 
Go to the Controller folder in your API application and right click >> Add >> Controller >> Select Web API 2 Controller-Empty.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Click "Add".
 
Now, we will write the logic for performing two tasks - one for binding the location of the company and the second for adding company details.
 
We will go to the controller class and set the routing to make it more user-friendly by writing the below code.
  1. using AngularAPIExample.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web.Http;  
  6.   
  7. namespace AngularAPIExample.Controllers  
  8. {  
  9.     [RoutePrefix("Api/BranchAPI")]  
  10.     public class BranchController : ApiController  
  11.     {  
  12.         [HttpGet]  
  13.         [Route("AllBranch")]  
  14.         public IEnumerable<BranchDetail> BranchDetails()  
  15.         {  
  16.             IEnumerable<BranchDetail> lstBranch = new List<BranchDetail>();  
  17.             string response = "";  
  18.             try  
  19.             {  
  20.                 using (AngularDBEntities objEntity = new AngularDBEntities())  
  21.                 {  
  22.                     lstBranch = objEntity.BranchDetails.ToList();  
  23.                 }  
  24.             }  
  25.             catch (Exception ex)  
  26.             {  
  27.                 response = ex.ToString();  
  28.             }  
  29.             return lstBranch;  
  30.         }  
  31.   
  32.         [HttpPost]  
  33.         [Route("AddCompanyDetails")]  
  34.         public string AddCompany( CompanyDetail companyDetails)  
  35.         {  
  36.              
  37.             string response = "";  
  38.             try  
  39.             {  
  40.                 using (AngularDBEntities objEntity = new AngularDBEntities())  
  41.                 {  
  42.                     objEntity.CompanyDetails.Add(companyDetails);  
  43.                     int result = objEntity.SaveChanges();  
  44.                     if(result > 0)  
  45.                     {  
  46.                         response = "Inserted";  
  47.                     }  
  48.                     else  
  49.                     {  
  50.                         response = "Faild";  
  51.                     }  
  52.                 }  
  53.             }  
  54.             catch (Exception ex)  
  55.             {  
  56.                 response = ex.ToString();  
  57.             }  
  58.             return response;  
  59.         }  
  60.     }  
  61. }  
Now, our API has completed.
 
Step 5: Check Angular CLI 8
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Step 6: Create an Angular 8 Project
 
Let's create an Angular8 project using the following command.
 
ng new CheckboxExample 
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
The Angular project has been created.
 
We are using Visual Studio Code for writing the Angular code for UI applications so, first make sure it is installed. If you have not installed it yet, then go to this link for download.
 
Step 7: Set Visual Studio Code for Angular code
 
Open Visual Studio Code and check the Angular version in package.json.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Now, go inside the folder and open the project inside Visual Studio Code.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Select the folder.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Step 8: Generate Angular Component
 
Open the command prompt and type the following command to generate an Angular component and hit Enter.
 
ng g c branch
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Step 9: Generate Angular Service
 
Open the command prompt and type the following command to generate an Angular model class and hit Enter.
 
ng g class model/branch
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Step 10: Generate Angular Model Class
 
Open the command prompt and type the following command to generate an Angular service and hit Enter.
 
ng g s service/branch
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Now, let us take a final look.
 
CheckBox Example In Angular 8 Using Web API And SQL Server 
 
Step 10: Set Properties in Model Class
  1. export class Branch {  
  2.     BranchId:number;  
  3.     BranchName:string;  
  4. }  
Step 11 - Write Code in Angular Service
 
Now, open branch.service.ts and first import necessary class and libraries and then make calls to the WebAPI methods. 
  1. import { Injectable } from '@angular/core';  
  2. import { Observable } from 'rxjs';  
  3. import { Branch } from '../model/branch';  
  4. import { HttpClient, HttpHeaders } from '@angular/common/http';  
  5.   
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class BranchService {  
  10.   
  11.   url = "http://localhost:56924/";  
  12.   
  13.   constructor(private http: HttpClient) { }  
  14.   AllBranch(): Observable<Branch[]> {  
  15.     return this.http.get<Branch[]>(this.url + 'Api/BranchAPI/AllBranch')  
  16.   }  
  17.   InserCompany(companyName:string,branches:string)  
  18.   {  
  19. debugger;  
  20.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json'}) };    
  21.     let companyDetails = {  
  22.       CompanyName: companyName,  
  23.       BranchName:branches  
  24.          };    
  25.     return this.http.post<string>(this.url + 'Api/BranchAPI/AddCompanyDetails/',    
  26.     companyDetails, httpOptions);    
  27.   }  
  28. }   
Step 12: Write code in Angular Component.ts
 
Now, open branch.component.ts and first import necessary class and libraries and then make calls to the WebAPI methods. 
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Branch } from '../model/branch';  
  3. import { BranchService } from '../service/branch.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-branch',  
  7.   templateUrl: './branch.component.html',  
  8.   styleUrls: ['./branch.component.css']  
  9. })  
  10. export class BranchComponent implements OnInit {  
  11.   lstBranch :Branch[];  
  12.   
  13.   resultText=[];  
  14.   values:string;  
  15.  count:number=0;  
  16.  errorMsg:string;  
  17.  companyName:string;  
  18.  constructor(private service: BranchService) {  
  19.     
  20.   }  
  21.   ngOnInit() {  
  22.    this.service.AllBranch().subscribe(res => {  
  23.      this.lstBranch = res;  
  24.    });  
  25.  }  
  26.   
  27.  onChange(branchNamae:string,event) {  
  28.   this.errorMsg="";  
  29.    const checked = event.target.checked;  
  30.   
  31.     if (checked) {  
  32.       this.resultText.push(branchNamae);  
  33.      
  34.        } else {  
  35.          const index = this.resultText.indexOf(branchNamae);  
  36.          this.resultText.splice(index, 1);  
  37.      }  
  38.      this.values=this.resultText.toString();  
  39.      const count=this.resultText.length;  
  40.      this.count=count;  
  41.   }  
  42.   
  43.   Save() {  
  44.   
  45.   const count=this.resultText.length;  
  46.   
  47.   if(count == 0)  
  48.   {  
  49.     this.errorMsg="Select at least one branch";  
  50.   }  
  51.   else  
  52.   {  
  53.     this.count=count;  
  54.   }  
  55.     
  56.    this.service.InserCompany(this.companyName, this.resultText.toString()).subscribe(result=>{  
  57. alert(result);  
  58.    });  
  59.  }  
  60. }  
Step 13: Write code in Angular Component.html
 
Now, open branch.component.htmland write html code for designing our UI
  1. <div class="container">  
  2.   <h1>Check box example</h1>  
  3.   <hr>  
  4.   <div class="col-md-7">  
  5.   
  6.       <div class="row" style="font-size:18px">  
  7. <div class="col-md-3">Company Name</div>  
  8. <div class="col-md-9"><input type="text" class="form-control" [(ngModel)]="companyName"></div></div>  
  9. <br>  
  10. <div class="row">  
  11.     <div class="col-md-3"></div>  
  12.         <div class="col-md-9">  
  13.           <label *ngFor="let branch of lstBranch;" class="form-control">  
  14.   
  15.             <input type="checkbox" value=" {{branch.BranchId}}" (change)="onChange(branch.BranchName,$event)">  
  16.               {{branch.BranchName}}<br>  
  17.   
  18.           </label>  
  19.           <br>           
  20.           <label style="font-size:18px">{{values}}</label>    
  21.           <label style="font-size:18px">({{count}})</label>    
  22.           <label style="font-size:18px;color: red">{{errorMsg}}</label><br>       
  23.         </div>   
  24.       <br>           
  25.     </div>  
  26.     <button type="button" (click)="Save()" class="btn btn-primary">submit</button>  
  27.   </div>  
  28. </div>  
Step 14: Set app.module.ts
 
Now, let's get all the required libraries in app.module.ts.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6. import { BranchComponent } from './branch/branch.component';  
  7. import { HttpClientModule } from '@angular/common/http';  
  8. import { FormsModule } from '@angular/forms';  
  9.   
  10. @NgModule({  
  11.   declarations: [  
  12.     AppComponent,  
  13.     BranchComponent  
  14.   ],  
  15.   imports: [  
  16.     BrowserModule,  
  17.     AppRoutingModule,  
  18.     HttpClientModule,  
  19.     FormsModule  
  20.   ],  
  21.   providers: [],  
  22.   bootstrap: [AppComponent]  
  23. })  
  24. export class AppModule { }  
Step 15: Set bootstrap library in index.html for good look
 
Open index.html and write the below link inside the head tag and you can also install by NPM.
  1. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">  
  2. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>  
  3. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>  
Step 16: Set CORS (Cross-Origin Resource Sharing)
 
 Go to the Web API project.
 
Download a NuGet package for CORS. Go to NuGet Package Manager and download the following file.
 
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
After that, go to App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code. 
 
Add namespace
  1. using System.Web.Http.Cors;  
After that, add the below code inside Register method.
  1. var cors = new EnableCorsAttribute("*""*""*");  
  2. config.EnableCors(cors);  
Step 17: Run
 
We have completed all the needed code functionality. Before running the application, first, make sure to save your work or file.
 
Now, let's run the app and see how it works. 
 
Open TERMINAL and write the following command to run the program.
 
ng serve -o
 
The output looks like the following image. It's a stunning UI that's been created.
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
After selecting some branches:
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
If we click submit button without checking any branch then it will give the below output:
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Now fill the text box and select branches and click submit:
 
CheckBox Example In Angular 8 Using Web API And SQL Server
 
Now see the final operation:
 
CheckBox Example In Angular 8 Using Web API And SQL Server