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,
Prerequisites
- Visual studio
- Sql Server
- Node.js version > 10
- Angular 9
- Visual studio code
- Bootstrap
- 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.
- CREATE TABLE [dbo].[userdetails]
- (
- [userid] [INT] IDENTITY(1, 1) NOT NULL,
- [username] [VARCHAR](50) NULL,
- [emailid] [VARCHAR](150) NULL,
- [gender] [VARCHAR](50) NULL,
- [address] [VARCHAR](500) NULL,
- [mobileno] [VARCHAR](15) NULL,
- [pincode] [VARCHAR](10) NULL,
- CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED ( [userid] 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
-
- SET IDENTITY_INSERT [dbo].[UserDetails] ON
-
- INSERT [dbo].[userdetails]
- ([userid],
- [username],
- [emailid],
- [gender],
- [address],
- [mobileno],
- [pincode])
- VALUES (9,
- N'Keke',
- N'[email protected]',
- N'Male ',
- N'Trochu',
- N'+91 9660463415',
- N'525477')
-
- INSERT [dbo].[userdetails]
- ([userid],
- [username],
- [emailid],
- [gender],
- [address],
- [mobileno],
- [pincode])
- VALUES (12,
- N'Preston',
- N'[email protected]',
- N'Male ',
- N'Campagna',
- N'+91 9794644638',
- N'368195')
-
- INSERT [dbo].[userdetails]
- ([userid],
- [username],
- [emailid],
- [gender],
- [address],
- [mobileno],
- [pincode])
- VALUES (1017,
- N'mithilesh kumar',
- N'[email protected]',
- N'male',
- N'hyderabad',
- N'093450945',
- N'500025')
-
- 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.
Click OK and you will see the templates. Select the Web API template.
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 Add button
Give the server the name of the SQL server and its credential then select database and test connection then click the ok button.
Click Next button.
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
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.
- using AngularApp.Models;
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace AngularApp.Controllers {
- [RoutePrefix("Api/User")]
- public class UserAPIController: ApiController {
- AngularDBEntities objEntity = new AngularDBEntities();
- [HttpGet]
- [Route("GetUserDetails")]
- public IQueryable < UserDetail > GetUser() {
- try {
- return objEntity.UserDetails;
- } catch (Exception) {
- throw;
- }
- }
- }
- }
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.
.............................
Once created, the project should look like this.
Step 7 - Check Angular dependency
Go to in package.json file and check Angular dependency.
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,
After it's installed successfully, we can check in the package.json file
Step 9 - Install bootstrap
Now, we will install bootstrap to build a beautiful UI of our Angular application.
npm install bootstrap --save
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
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.
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
- export class UserDetail {
- UserId: number;
- UserName: string;
- EmailId: string;
- Gender: string;
- Address: string;
- MobileNo: string;
- PinCode: string;
- }
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.
- <div class="container">
- <h1>User details using dailog box in angular</h1>
- <hr>
- <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
- <ng-container matColumnDef="UserId">
- <th style="width: 100px;" mat-header-cell *matHeaderCellDef> User Id </th>
- <td mat-cell *matCellDef="let element"> {{element.UserId}} </td>
- </ng-container>
- <!-- User Name Column -->
- <ng-container matColumnDef="UserName">
- <th style="width: 150px;" mat-header-cell *matHeaderCellDef> User Name </th>
- <td mat-cell *matCellDef="let element"> {{element.UserName}} </td>
- </ng-container>
- <!-- EmailId Column -->
- <ng-container matColumnDef="EmailId">
- <th style="width: 150px;" mat-header-cell *matHeaderCellDef> EmailId </th>
- <td mat-cell *matCellDef="let element"> {{element.EmailId}} </td>
- </ng-container>
- <!-- Mobile Column -->
- <ng-container matColumnDef="MobileNo">
- <th mat-header-cell *matHeaderCellDef style="width: 200px;"> MobileNo </th>
- <td mat-cell *matCellDef="let element"> {{element.MobileNo}} </td>
- </ng-container>
- <ng-container matColumnDef="Action" >
- <th mat-header-cell *matHeaderCellDef> Action </th>
- <td mat-cell *matCellDef="let element">
- <button (click)="openDialog(element)" mat-raised-button class="btn btn-primary">
- <span>Detail</span>
- </button>
- </td>
- </ng-container>
- <tr mat-header-row *matHeaderRowDef="displayedColumns"
- style="background-color:darkblue;"></tr>
- <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
- </table>
- </div>
And now open user.component.ts and first import the necessary library and then write the below code.
- import {
- Component,
- OnInit
- } from '@angular/core';
- import {
- MatTableDataSource
- } from '@angular/material/table';
- import {
- UserDetail
- } from '../user';
- import {
- SelectionModel
- } from '@angular/cdk/collections';
- import {
- UserService
- } from '../service/user.service';
- import {
- MatDialog,
- MatDialogConfig
- } from "@angular/material/dialog";
- import {
- UserDetailComponent
- } from '../user-detail/user-detail.component';
- @Component({
- selector: 'app-user',
- templateUrl: './user.component.html',
- styleUrls: ['./user.component.css']
- })
- export class UserComponent implements OnInit {
- TotalRow: number;
- displayedColumns: string[] = ['UserId', 'UserName', 'EmailId', 'MobileNo', 'Action'];
- dataSource: MatTableDataSource < UserDetail > ;
- selection = new SelectionModel < UserDetail > (true, []);
- constructor(private service: UserService, private dialog: MatDialog, ) {}
- ngOnInit(): void {
- this.LoadData();
- }
- LoadData() {
- this.service.getUsers().subscribe(result => {
- this.dataSource = new MatTableDataSource(result);
- })
- }
- openDialog(data) {
- debugger;
- const dialogConfig = new MatDialogConfig();
- dialogConfig.disableClose = true;
- dialogConfig.autoFocus = true;
- dialogConfig.position = {
- 'top': '100px',
- 'left': '500px'
- };
- dialogConfig.width = '500px';
- dialogConfig.height = '500px';
- dialogConfig.data = {
- userId: data.UserId
- };
- this.dialog.open(UserDetailComponent, dialogConfig);
- }
- }
Go inside the user-detail folder and open user-detail.component.html file and write the below code.
- <mat-dialog-content>
- <mat-toolbar color="accent" style="background-color:darkblue;">
-
- User Details
- </mat-toolbar>
- <br>
- <table class="table">
- <tr>
- <th> UserId </th>
- <td> {{UserId}} </td>
- </tr>
- <tr>
- <th> User Name </th>
- <td> {{UserName}} </td>
- </tr>
- <tr>
- <th> EmailId </th>
- <td> {{EmailId}} </td>
- </tr>
- <tr>
- <th> Gender </th>
- <td> {{Gender}} </td>
- </tr>
- <tr>
- <th> Address </th>
- <td> {{Address}} </td>
- </tr>
- <tr>
- <th> MobileNo </th>
- <td> {{MobileNo}} </td>
- </tr>
- <tr>
- <th> PinCode </th>
- <td> {{PinCode}} </td>
- </tr>
- </table>
- </mat-dialog-content>
- <mat-dialog-actions align="center">
- <button class="mat-raised-button btn btn-danger" (click)="close()">Close</button>
- </mat-dialog-actions>
Go inside the user-detail folder and open user-detail.component.ts file and write the below code.
- import {
- Component,
- OnInit,
- Inject
- } from '@angular/core';
- import {
- UserService
- } from '../service/user.service';
- import {
- MatDialogRef,
- MAT_DIALOG_DATA
- } from '@angular/material/dialog';
- import {
- UserComponent
- } from '../user/user.component';
- import {
- UserDetail
- } from '../user';
- @Component({
- selector: 'app-user-detail',
- templateUrl: './user-detail.component.html',
- styleUrls: ['./user-detail.component.css']
- })
- export class UserDetailComponent implements OnInit {
- UserId: number;
- UserName: string;
- EmailId: string;
- Gender: string;
- Address: string;
- MobileNo: string;
- PinCode: string;
- UserDetail: UserDetail;
- constructor(private service: UserService, private dialogRef: MatDialogRef < UserComponent > , @Inject(MAT_DIALOG_DATA) data) {
- this.UserId = data.userId
- }
- ngOnInit(): void {
- this.service.getUsers().subscribe(result => {
- this.UserDetail = result.find(a => a.UserId == this.UserId);
- this.UserName = this.UserDetail.UserName;
- this.EmailId = this.UserDetail.EmailId;
- this.Gender = this.UserDetail.Gender;
- this.Address = this.UserDetail.Address;
- this.MobileNo = this.UserDetail.MobileNo;
- this.PinCode = this.UserDetail.PinCode;
- })
- }
- close() {
- this.dialogRef.close();
- }
- }
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.
- import {
- Injectable
- } from '@angular/core';
- import {
- Observable
- } from 'rxjs';
- import {
- HttpClient,
- HttpHeaders
- } from '@angular/common/http';
- import {
- UserDetail
- } from '../user';
- @Injectable({
- providedIn: 'root'
- })
- export class UserService {
- apiUrl: string = "http://localhost:50685/Api/User/";
- constructor(private http: HttpClient) {}
- getUsers(): Observable < UserDetail[] > {
- return this.http.get < UserDetail[] > (`${this.apiUrl}GetUserDetails`);
- }
- }
Step 17 - Add Dependecy NPM in app.module.ts
Go to app.module.ts file and add dependency.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import { UserComponent } from './user/user.component';
- import { MatInputModule } from '@angular/material/input';
- import { MatDialogModule} from '@angular/material/dialog'
- import { MatCheckboxModule } from '@angular/material/checkbox';
- import { MatSelectModule } from '@angular/material/select';
- import { MatTableModule } from '@angular/material/table';
- import { MatToolbarModule} from '@angular/material/toolbar';
- import {HttpClientModule} from '@angular/common/http';
- import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
- import { UserDetailComponent } from './user-detail/user-detail.component';
-
- @NgModule({
- declarations: [
- AppComponent,
- UserComponent,
- UserDetailComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,
- MatCheckboxModule,
- MatDialogModule,
- MatToolbarModule,
- MatInputModule,
- MatSelectModule,
- MatTableModule,
- HttpClientModule,
- BrowserAnimationsModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- 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.
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
- var cors = new EnableCorsAttribute("*", "*", "*");
- 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.
Click on Details button.
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.