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
- Visual Studio
- SQL Server
- js version > 10
- AngularCLI v8.0.3
- Visual studio code
- 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
- CREATE TABLE [dbo].[BranchDetails](
- [BranchId] [int] IDENTITY(1,1) NOT NULL,
- [BranchName] [varchar](100) NULL,
- CONSTRAINT [PK_BranchDetails] PRIMARY KEY CLUSTERED
- (
- [BranchId] 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
-
- SET ANSI_PADDING OFF
- GO
Company Details
- CREATE TABLE [dbo].[CompanyDetails](
- [CompnayID] [int] IDENTITY(1,1) NOT NULL,
- [BranchName] [nvarchar](max) NULL,
- [CompanyName] [varchar](100) NULL,
- CONSTRAINT [PK_CompanyDetails] PRIMARY KEY CLUSTERED
- (
- [CompnayID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
-
- GO
-
- SET ANSI_PADDING OFF
- 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.
Click OK
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.
Click the "Add" button.
Click "Next".
Give the SQL server name and its credentials. Then, select the database and test connection. Click OK.
Click "Next".
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.
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.
- using AngularAPIExample.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Http;
-
- namespace AngularAPIExample.Controllers
- {
- [RoutePrefix("Api/BranchAPI")]
- public class BranchController : ApiController
- {
- [HttpGet]
- [Route("AllBranch")]
- public IEnumerable<BranchDetail> BranchDetails()
- {
- IEnumerable<BranchDetail> lstBranch = new List<BranchDetail>();
- string response = "";
- try
- {
- using (AngularDBEntities objEntity = new AngularDBEntities())
- {
- lstBranch = objEntity.BranchDetails.ToList();
- }
- }
- catch (Exception ex)
- {
- response = ex.ToString();
- }
- return lstBranch;
- }
-
- [HttpPost]
- [Route("AddCompanyDetails")]
- public string AddCompany( CompanyDetail companyDetails)
- {
-
- string response = "";
- try
- {
- using (AngularDBEntities objEntity = new AngularDBEntities())
- {
- objEntity.CompanyDetails.Add(companyDetails);
- int result = objEntity.SaveChanges();
- if(result > 0)
- {
- response = "Inserted";
- }
- else
- {
- response = "Faild";
- }
- }
- }
- catch (Exception ex)
- {
- response = ex.ToString();
- }
- return response;
- }
- }
- }
Now, our API has completed.
Step 5: Check Angular CLI 8
Step 6: Create an Angular 8 Project
Let's create an Angular8 project using the following command.
ng new CheckboxExample
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.
Now, go inside the folder and open the project inside Visual Studio Code.
Select the folder.
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
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
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
Now, let us take a final look.
Step 10: Set Properties in Model Class
- export class Branch {
- BranchId:number;
- BranchName:string;
- }
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.
- import { Injectable } from '@angular/core';
- import { Observable } from 'rxjs';
- import { Branch } from '../model/branch';
- import { HttpClient, HttpHeaders } from '@angular/common/http';
-
- @Injectable({
- providedIn: 'root'
- })
- export class BranchService {
-
- url = "http://localhost:56924/";
-
- constructor(private http: HttpClient) { }
- AllBranch(): Observable<Branch[]> {
- return this.http.get<Branch[]>(this.url + 'Api/BranchAPI/AllBranch')
- }
- InserCompany(companyName:string,branches:string)
- {
- debugger;
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}) };
- let companyDetails = {
- CompanyName: companyName,
- BranchName:branches
- };
- return this.http.post<string>(this.url + 'Api/BranchAPI/AddCompanyDetails/',
- companyDetails, httpOptions);
- }
- }
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.
- import { Component, OnInit } from '@angular/core';
- import { Branch } from '../model/branch';
- import { BranchService } from '../service/branch.service';
-
- @Component({
- selector: 'app-branch',
- templateUrl: './branch.component.html',
- styleUrls: ['./branch.component.css']
- })
- export class BranchComponent implements OnInit {
- lstBranch :Branch[];
-
- resultText=[];
- values:string;
- count:number=0;
- errorMsg:string;
- companyName:string;
- constructor(private service: BranchService) {
-
- }
- ngOnInit() {
- this.service.AllBranch().subscribe(res => {
- this.lstBranch = res;
- });
- }
-
- onChange(branchNamae:string,event) {
- this.errorMsg="";
- const checked = event.target.checked;
-
- if (checked) {
- this.resultText.push(branchNamae);
-
- } else {
- const index = this.resultText.indexOf(branchNamae);
- this.resultText.splice(index, 1);
- }
- this.values=this.resultText.toString();
- const count=this.resultText.length;
- this.count=count;
- }
-
- Save() {
-
- const count=this.resultText.length;
-
- if(count == 0)
- {
- this.errorMsg="Select at least one branch";
- }
- else
- {
- this.count=count;
- }
-
- this.service.InserCompany(this.companyName, this.resultText.toString()).subscribe(result=>{
- alert(result);
- });
- }
- }
Step 13: Write code in Angular Component.html
Now, open branch.component.htmland write html code for designing our UI
- <div class="container">
- <h1>Check box example</h1>
- <hr>
- <div class="col-md-7">
-
- <div class="row" style="font-size:18px">
- <div class="col-md-3">Company Name</div>
- <div class="col-md-9"><input type="text" class="form-control" [(ngModel)]="companyName"></div></div>
- <br>
- <div class="row">
- <div class="col-md-3"></div>
- <div class="col-md-9">
- <label *ngFor="let branch of lstBranch;" class="form-control">
-
- <input type="checkbox" value=" {{branch.BranchId}}" (change)="onChange(branch.BranchName,$event)">
- {{branch.BranchName}}<br>
-
- </label>
- <br>
- <label style="font-size:18px">{{values}}</label>
- <label style="font-size:18px">({{count}})</label>
- <label style="font-size:18px;color: red">{{errorMsg}}</label><br>
- </div>
- <br>
- </div>
- <button type="button" (click)="Save()" class="btn btn-primary">submit</button>
- </div>
- </div>
Step 14: Set app.module.ts
Now, let's get all the required libraries in app.module.ts.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import { BranchComponent } from './branch/branch.component';
- import { HttpClientModule } from '@angular/common/http';
- import { FormsModule } from '@angular/forms';
-
- @NgModule({
- declarations: [
- AppComponent,
- BranchComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- HttpClientModule,
- FormsModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- 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.
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
- <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.
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
- using System.Web.Http.Cors;
After that, add the below code inside Register method.
- var cors = new EnableCorsAttribute("*", "*", "*");
- 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.
After selecting some branches:
If we click submit button without checking any branch then it will give the below output:
Now fill the text box and select branches and click submit:
Now see the final operation: