Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL

Introduction

 
In this article, I'm going to create an application to get user details in a Dialog Box in Angular 9 with Angular material using Web API with the help of an example. A  SQL Server database is the back-end and a Web API is used to provide data connectivity between the database and the front-end application for building RESTful services.
 
On the UI side, I will use Bootstrap and Angular material to create a rich, interactive, device-independent user experience so as to building a beautiful UI. In this example, I will bind user details in a short format ( i.e. we will see only necessary columns) and when we want to see the records in detail of a particular user, then will click a specific row. After that, it will show records in a popup window and then clicking the Close button will close the popup. Let us see step by step.
 
I'm using Visual Studio Code as a tool to build my application. If you don't have Visual Studio Code in your system, then first you have to download and install it.  Here is the Visual Studio Code download link: Download Visual Studio Code Editor.
 
First, take a look at our output,
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Prerequisites
  1. Visual studio
  2. Sql Server
  3. Node.js version > 10
  4. Angular 9
  5. Visual studio code
  6. Bootstrap
  7. Angular material
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 User Details. 
  1. CREATE TABLE [dbo].[userdetails]   
  2.   (   
  3.      [userid]   [INT] IDENTITY(1, 1) NOT NULL,   
  4.      [username] [VARCHAR](50) NULL,   
  5.      [emailid]  [VARCHAR](150) NULL,   
  6.      [gender]   [VARCHAR](50) NULL,   
  7.      [address]  [VARCHAR](500) NULL,   
  8.      [mobileno] [VARCHAR](15) NULL,   
  9.      [pincode]  [VARCHAR](10) NULL,   
  10.      CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED ( [userid] ASC )WITH (   
  11.      pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,   
  12.      allow_row_locks = on, allow_page_locks = onON [PRIMARY]   
  13.   )   
  14. ON [PRIMARY]   
  15.   
  16. go   
  17.   
  18. SET ansi_padding OFF   
  19.   
  20. go   
  21.   
  22. SET IDENTITY_INSERT [dbo].[UserDetails] ON   
  23.   
  24. INSERT [dbo].[userdetails]   
  25.        ([userid],   
  26.         [username],   
  27.         [emailid],   
  28.         [gender],   
  29.         [address],   
  30.         [mobileno],   
  31.         [pincode])   
  32. VALUES (9,   
  33.         N'Keke',   
  34.         N'[email protected]',   
  35.         N'Male ',   
  36.         N'Trochu',   
  37.         N'+91 9660463415',   
  38.         N'525477')   
  39.   
  40. INSERT [dbo].[userdetails]   
  41.        ([userid],   
  42.         [username],   
  43.         [emailid],   
  44.         [gender],   
  45.         [address],   
  46.         [mobileno],   
  47.         [pincode])   
  48. VALUES (12,   
  49.         N'Preston',   
  50.         N'[email protected]',   
  51.         N'Male ',   
  52.         N'Campagna',   
  53.         N'+91 9794644638',   
  54.         N'368195')   
  55.   
  56. INSERT [dbo].[userdetails]   
  57.        ([userid],   
  58.         [username],   
  59.         [emailid],   
  60.         [gender],   
  61.         [address],   
  62.         [mobileno],   
  63.         [pincode])   
  64. VALUES (1017,   
  65.         N'mithilesh kumar',   
  66.         N'[email protected]',   
  67.         N'male',   
  68.         N'hyderabad',   
  69.         N'093450945',   
  70.         N'500025')   
  71.   
  72. SET IDENTITY_INSERT [dbo].[UserDetails] OFF   
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 a database. Go to Visual Studio >> File >> New >> Project, and select Web Application.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Click OK and you will see the templates. Select the Web API template.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
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,
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Click Add button
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Click Next button
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Give the server the name of the SQL server and its credential then select database and test connection then click the ok button.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Click Next button.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Select UserDetails table and click Finish button
 
Step 4 - Add API controller logic
 
Go to the Controller folder in our API Application and right-click >> Add >> Controller >> Select Web API 2 Controller-Empty
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Click Add button.
 
Now we will write the logic for binding data record functionality. We will go to the controller class and set the routing to make it more user-friendly by writing the below code.
  1. using AngularApp.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Net;  
  7. using System.Net.Http;  
  8. using System.Web.Http;  
  9. namespace AngularApp.Controllers {  
  10.     [RoutePrefix("Api/User")]  
  11.     public class UserAPIController: ApiController {  
  12.         AngularDBEntities objEntity = new AngularDBEntities();  
  13.         [HttpGet]  
  14.         [Route("GetUserDetails")]  
  15.         public IQueryable < UserDetail > GetUser() {  
  16.             try {  
  17.                 return objEntity.UserDetails;  
  18.             } catch (Exception) {  
  19.                 throw;  
  20.             }  
  21.         }  
  22.     }  
  23. }  
Now, our API has been completed and as you may see from the above code, it has the functionality to add, replace, update, and delete records to the table.
 
Step 5 - Install Angular CLI
 
Now we will install Angular CLI through the below command. But before that just check whether Node and NPM are installed or not. And also we are using Visual Studio code as we are writing Angular code for UI applications. So first, make sure it's installed. If you have not installed it then go to this link for downloading.
 
Let's install CLI to open a cmd and run the following command to install
 
npm install -g @angular/cli
 
Step 6 - Create am Anguglar project

Now, open Visual Studio Code and create a project.
 
Open TERMINAL in Visual Studio Code and type the following syntax to create a new project. We will name it BindRecords. 
 
ng new BindRecords

After that, hit ENTER. It will take a while to create the project.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
.............................
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Once created, the project should look like this.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL

Step 7 - Check Angular dependency
 
Go to in package.json file and check Angular dependency.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Step 8 - Install and Configure Angular Material Theme
 
As I mentioned earlier, we will use Angular Material theme to create a rich, interactive and device-oriented UI for our Web app.
 
Let's install the Angular Material theme.
 
Open TERMINAL again and write the below command:
 
npm install --save @angular/material @angular/cdk @angular/animations
 
If you want to learn more about Angular Material, visit here: link.
 
If you have an existing Angular Project, Open Terminal/Command Prompt in the same folder as your project and write,
 
ng add @angular/material
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
After it's  installed successfully, we can check in the package.json file
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Step 9 - Install bootstrap
 
Now, we will install bootstrap to build a beautiful UI of our Angular application.
 
npm install bootstrap --save
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Step 11 - Create Components
 
Now, we can create some components to provide the UI.
 
I'm going to create a new component, User and Detail User.
 
Go to the TERMINAL and go our Angular project location using the following command.
 
ng g c User
ng g c UserDetail 
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Step 12 - Create Service
 
Now, we will create a service.
 
Open the TERMINAL and write the below command,
 
ng g s user
 
Press ENTER and you will see two service files.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
Step 13 - Create a model class
 
Now, we create a class like model class.
 
Open TERMINAL and write the below command,
 
ng g class UserDetails
  1. export class UserDetail {  
  2.     UserId: number;  
  3.     UserName: string;  
  4.     EmailId: string;  
  5.     Gender: string;  
  6.     Address: string;  
  7.     MobileNo: string;  
  8.     PinCode: string;  
  9. }  
Step 14 - Implement component UI
 
Now we will write our logic to bind and delete records.
 
Go inside the user folder and open user.component.html file and write the below code.
  1. <div class="container">  
  2.     <h1>User details using dailog box in angular</h1>  
  3.     <hr>  
  4.         <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">  
  5.             <ng-container matColumnDef="UserId">  
  6.                 <th style="width: 100px;" mat-header-cell *matHeaderCellDef> User Id </th>  
  7.                 <td mat-cell *matCellDef="let element"> {{element.UserId}} </td>  
  8.             </ng-container>  
  9.             <!-- User Name Column -->  
  10.             <ng-container matColumnDef="UserName">  
  11.                 <th style="width: 150px;" mat-header-cell *matHeaderCellDef> User Name </th>  
  12.                 <td mat-cell *matCellDef="let element"> {{element.UserName}} </td>  
  13.             </ng-container>  
  14.             <!-- EmailId Column -->  
  15.             <ng-container matColumnDef="EmailId">  
  16.                 <th style="width: 150px;" mat-header-cell *matHeaderCellDef> EmailId </th>  
  17.                 <td mat-cell *matCellDef="let element"> {{element.EmailId}} </td>  
  18.             </ng-container>  
  19.             <!-- Mobile Column -->  
  20.             <ng-container matColumnDef="MobileNo">  
  21.                 <th mat-header-cell *matHeaderCellDef style="width: 200px;"> MobileNo </th>  
  22.                 <td mat-cell *matCellDef="let element"> {{element.MobileNo}} </td>  
  23.             </ng-container>  
  24.             <ng-container matColumnDef="Action" >  
  25.                 <th mat-header-cell *matHeaderCellDef> Action </th>  
  26.                 <td mat-cell *matCellDef="let element">  
  27.                     <button (click)="openDialog(element)" mat-raised-button class="btn btn-primary">  
  28.                         <span>Detail</span>  
  29.                     </button>  
  30.                 </td>  
  31.             </ng-container>  
  32.             <tr mat-header-row *matHeaderRowDef="displayedColumns"  
  33. style="background-color:darkblue;"></tr>  
  34.             <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>  
  35.         </table>  
  36.     </div>  
And now open user.component.ts and first import the necessary library and then write the below code.
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     MatTableDataSource  
  7. } from '@angular/material/table';  
  8. import {  
  9.     UserDetail  
  10. } from '../user';  
  11. import {  
  12.     SelectionModel  
  13. } from '@angular/cdk/collections';  
  14. import {  
  15.     UserService  
  16. } from '../service/user.service';  
  17. import {  
  18.     MatDialog,  
  19.     MatDialogConfig  
  20. } from "@angular/material/dialog";  
  21. import {  
  22.     UserDetailComponent  
  23. } from '../user-detail/user-detail.component';  
  24. @Component({  
  25.     selector: 'app-user',  
  26.     templateUrl: './user.component.html',  
  27.     styleUrls: ['./user.component.css']  
  28. })  
  29. export class UserComponent implements OnInit {  
  30.     TotalRow: number;  
  31.     displayedColumns: string[] = ['UserId''UserName''EmailId''MobileNo''Action'];  
  32.     dataSource: MatTableDataSource < UserDetail > ;  
  33.     selection = new SelectionModel < UserDetail > (true, []);  
  34.     constructor(private service: UserService, private dialog: MatDialog, ) {}  
  35.     ngOnInit(): void {  
  36.         this.LoadData();  
  37.     }  
  38.     LoadData() {  
  39.         this.service.getUsers().subscribe(result => {  
  40.             this.dataSource = new MatTableDataSource(result);  
  41.         })  
  42.     }  
  43.     openDialog(data) {  
  44.         debugger;  
  45.         const dialogConfig = new MatDialogConfig();  
  46.         dialogConfig.disableClose = true;  
  47.         dialogConfig.autoFocus = true;  
  48.         dialogConfig.position = {  
  49.             'top''100px',  
  50.             'left''500px'  
  51.         };  
  52.         dialogConfig.width = '500px';  
  53.         dialogConfig.height = '500px';  
  54.         dialogConfig.data = {  
  55.             userId: data.UserId  
  56.         };  
  57.         this.dialog.open(UserDetailComponent, dialogConfig);  
  58.     }  
  59. }  
Go inside the user-detail folder and open user-detail.component.html file and write the below code.
  1. <mat-dialog-content>  
  2.     <mat-toolbar color="accent" style="background-color:darkblue;">  
  3.   
  4. User Details  
  5. </mat-toolbar>  
  6.     <br>  
  7.         <table class="table">  
  8.             <tr>  
  9.                 <th> UserId </th>  
  10.                 <td> {{UserId}} </td>  
  11.             </tr>  
  12.             <tr>  
  13.                 <th> User Name </th>  
  14.                 <td> {{UserName}} </td>  
  15.             </tr>  
  16.             <tr>  
  17.                 <th> EmailId </th>  
  18.                 <td> {{EmailId}} </td>  
  19.             </tr>  
  20.             <tr>  
  21.                 <th> Gender </th>  
  22.                 <td> {{Gender}} </td>  
  23.             </tr>  
  24.             <tr>  
  25.                 <th> Address </th>  
  26.                 <td> {{Address}} </td>  
  27.             </tr>  
  28.             <tr>  
  29.                 <th> MobileNo </th>  
  30.                 <td> {{MobileNo}} </td>  
  31.             </tr>  
  32.             <tr>  
  33.                 <th> PinCode </th>  
  34.                 <td> {{PinCode}} </td>  
  35.             </tr>  
  36.         </table>  
  37.     </mat-dialog-content>  
  38.     <mat-dialog-actions align="center">  
  39.         <button class="mat-raised-button btn btn-danger" (click)="close()">Close</button>  
  40.     </mat-dialog-actions>   
Go inside the user-detail folder and open user-detail.component.ts file and write the below code. 
  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     Inject  
  5. } from '@angular/core';  
  6. import {  
  7.     UserService  
  8. } from '../service/user.service';  
  9. import {  
  10.     MatDialogRef,  
  11.     MAT_DIALOG_DATA  
  12. } from '@angular/material/dialog';  
  13. import {  
  14.     UserComponent  
  15. } from '../user/user.component';  
  16. import {  
  17.     UserDetail  
  18. } from '../user';  
  19. @Component({  
  20.     selector: 'app-user-detail',  
  21.     templateUrl: './user-detail.component.html',  
  22.     styleUrls: ['./user-detail.component.css']  
  23. })  
  24. export class UserDetailComponent implements OnInit {  
  25.     UserId: number;  
  26.     UserName: string;  
  27.     EmailId: string;  
  28.     Gender: string;  
  29.     Address: string;  
  30.     MobileNo: string;  
  31.     PinCode: string;  
  32.     UserDetail: UserDetail;  
  33.     constructor(private service: UserService, private dialogRef: MatDialogRef < UserComponent > , @Inject(MAT_DIALOG_DATA) data) {  
  34.         this.UserId = data.userId  
  35.     }  
  36.     ngOnInit(): void {  
  37.         this.service.getUsers().subscribe(result => {  
  38.             this.UserDetail = result.find(a => a.UserId == this.UserId);  
  39.             this.UserName = this.UserDetail.UserName;  
  40.             this.EmailId = this.UserDetail.EmailId;  
  41.             this.Gender = this.UserDetail.Gender;  
  42.             this.Address = this.UserDetail.Address;  
  43.             this.MobileNo = this.UserDetail.MobileNo;  
  44.             this.PinCode = this.UserDetail.PinCode;  
  45.         })  
  46.     }  
  47.     close() {  
  48.         this.dialogRef.close();  
  49.     }  
  50. }  
Step 16 - Write logic of service for consuming api
 
Now, open user.service.tsand first import necessary class and libraries and then make calls to the WebAPI methods.
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Observable  
  6. } from 'rxjs';  
  7. import {  
  8.     HttpClient,  
  9.     HttpHeaders  
  10. } from '@angular/common/http';  
  11. import {  
  12.     UserDetail  
  13. } from '../user';  
  14. @Injectable({  
  15.     providedIn: 'root'  
  16. })  
  17. export class UserService {  
  18.     apiUrl: string = "http://localhost:50685/Api/User/";  
  19.     constructor(private http: HttpClient) {}  
  20.     getUsers(): Observable < UserDetail[] > {  
  21.         return this.http.get < UserDetail[] > (`${this.apiUrl}GetUserDetails`);  
  22.     }  
  23. }  
Step 17 - Add Dependecy NPM in app.module.ts
 
Go to app.module.ts file and add dependency.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppRoutingModule } from './app-routing.module';  
  4. import { AppComponent } from './app.component';  
  5. import { UserComponent } from './user/user.component';  
  6. import { MatInputModule } from '@angular/material/input';  
  7. import { MatDialogModule} from '@angular/material/dialog'  
  8. import { MatCheckboxModule } from '@angular/material/checkbox';  
  9. import { MatSelectModule } from '@angular/material/select';  
  10. import { MatTableModule } from '@angular/material/table';  
  11. import { MatToolbarModule} from '@angular/material/toolbar';  
  12. import {HttpClientModule} from '@angular/common/http';  
  13. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  14. import { UserDetailComponent } from './user-detail/user-detail.component';  
  15.   
  16. @NgModule({  
  17.    declarations: [  
  18.    AppComponent,  
  19.    UserComponent,  
  20.    UserDetailComponent  
  21. ],  
  22. imports: [  
  23.    BrowserModule,  
  24.    AppRoutingModule,  
  25.    MatCheckboxModule,  
  26.    MatDialogModule,  
  27.    MatToolbarModule,  
  28.    MatInputModule,  
  29.    MatSelectModule,  
  30.    MatTableModule,  
  31.    HttpClientModule,  
  32.    BrowserAnimationsModule  
  33.    ],  
  34.    providers: [],  
  35.    bootstrap: [AppComponent]  
  36. })  
  37. export class AppModule { }  
Step 18 - Calling the selector page or parant page
 
Go to app.component.html page and remove existing html code and add the below selector.
 
<app-user></app-user>
 
Finally, our coding part also has been completed.
 
Step 19 - 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.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 
After that, go to the App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
 
Add namespace
  1. var cors = new EnableCorsAttribute("*""*""*"); //origins,headers,methods  
  2. config.EnableCors(cors);   
Step 20 - Run
 
We have completed all needed code functionality for binding operations. Before running the application, first, make sure to save your work.
 
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 created with bind and delete operations.
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
Click on Details button. 
 
Create An Application To Get User Details In A Dialog Box In Angular With Angular Material Using Web API And SQL
 

Conclusion

 
We have learned how to perform an operation to get the details of a particular user in popup or model dialogs in Angular 9 and Angular Material using Web API and SQL Server. We started by installing and creating the create-angular-app then used it to create our Angular application. Next, we installed bootstrap in the Angular application. After that, we installed the Angular Material and used the get() details and particular get details methods to the HTTP request.
 
I hope you enjoyed this article. I'm always willing to reply to any query and comment.