Step 5. Build UI Application
First we have to make sure that we have Angular CLI installed.
Open command prompt and type below code and press ENTER:
npm install -g @angular/cli
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 name it Angularcrud.
Now, we can create some components to provide the UI.
I'm going to create a new component, Employee.
Go to the TERMINAL and go our angular project location using the following command:
cd projectName
Now, write the following command that will create a component.
ng g c employee Press ENTER. Note: you can use see the component is created.
Step 6. Create a Service Now, we will create a service. Open the TERMINAL and write the below command: ng g s employee Press ENTER and you will see two service files.
Now, we create a class like model class.
Open TERMINAL and write the below command:
ng g class employee Now, write all properties of the Employee class related to an employee that matches with the database.
- export class Employee {
- EmpId: string;
- EmpName: string;
- DateOfBirth: Date;
- EmailId: string;
- Gender: string;
- Address: string;
- PinCode: string;
- }
Now, open employee.service.ts and first import necessary class and libraries and then make calls to the WebAPI methods.
- import { Injectable } from '@angular/core';
- import { HttpClient } from '@angular/common/http';
- import { HttpHeaders } from '@angular/common/http';
- import { Observable } from 'rxjs';
- import { Employee } from './employee';
- After that we write all methods related to consume web in employee.service.ts
- @Injectable({
- providedIn: 'root'
- })
- export class EmployeeService {
- url = 'http://localhost:65389/Api/Employee';
- constructor(private http: HttpClient) { }
- getAllEmployee(): Observable<Employee[]> {
- return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');
- }
- getEmployeeById(employeeId: string): Observable<Employee> {
- return this.http.get<Employee>(this.url + '/GetEmployeeDetailsById/' + employeeId);
- }
- createEmployee(employee: Employee): Observable<Employee> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}) };
- return this.http.post<Employee>(this.url + '/InsertEmployeeDetails/',
- employee, httpOptions);
- }
- updateEmployee(employee: Employee): Observable<Employee> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}) };
- return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',
- employee, httpOptions);
- }
- deleteEmployeeById(employeeid: string): Observable<number> {
- const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}) };
- return this.http.delete<number>(this.url + '/DeleteEmployeeDetails?id=' +employeeid,
- httpOptions);
- }
- }
Our service is completed now.
If you consume the Web API, Angular blocks the URL and we called this issue CORS(Cross OriginResource Sharing).
First, let's resolve this problem.
Go to the Web API project.
Download a Nuget package for CORS. Go to NuGet Package ManagerConsole install this package:
Install-Package Microsoft.AspNet.WebApi.Cors
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;
- var cors = new EnableCorsAttribute("*","*","*");//origins,headers,methods
- config.EnableCors(cors);
Step 7. Install and Configure Angular Material Theme As I said earlier, we will use the Angular Material theme to create a rich, interactive, and device-oriented UI for our Web app.
Let's install Install Angular Material theme.
Open TERMINAL again and write the below command:
npm install --save @angular/material @angular/cdk @angular/animations
Now, let's all required libraries in app.module.ts. We also import a date picker because we'll use the date picker for date of birth field.
Now, open app.module.ts class and write the below code.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { EmployeeService } from './employee.service';
- import { FormsModule, ReactiveFormsModule } from '@angular/forms';
- import { HttpClientModule, HttpClient } from '@angular/common/http';
- import {
- MatButtonModule, MatMenuModule, MatDatepickerModule,MatNativeDateModule , MatIconModule, MatCardModule, MatSidenavModule,MatFormFieldModule,
- MatInputModule, MatTooltipModule, MatToolbarModule
- } from '@angular/material';
- import { MatRadioModule } from '@angular/material/radio';
- import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import { EmployeeComponent } from './employee/employee.component';
- @NgModule({
- declarations: [
- AppComponent,
- EmployeeComponent
- ],
- imports: [
- BrowserModule,
- FormsModule,
- ReactiveFormsModule,
- HttpClientModule,
- BrowserAnimationsModule,
- MatButtonModule,
- MatMenuModule,
- MatDatepickerModule,
- MatNativeDateModule,
- MatIconModule,
- MatRadioModule,
- MatCardModule,
- MatSidenavModule,
- MatFormFieldModule,
- MatInputModule,
- MatTooltipModule,
- MatToolbarModule,
- AppRoutingModule
- ],
- providers: [HttpClientModule, EmployeeService,MatDatepickerModule],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Now, we have to import library in styles.css file.
- @import '@angular/material/prebuilt-themes/indigo-pink.css';
Step 8. Design HTML
Let's design our HTML page now.
Open employee.component.html and write the below code.
- <div class="container">
- <mat-card>
- <mat-toolbar color="accent">
- <div align="center" style="color:white;text-align: right;">
- CRUD operation in Angular 7 using Web api and Sql Database
- </div>
- </mat-toolbar>
- <br><br>
- <mat-card-content>
- <form [formGroup]="employeeForm"(ngSubmit)="onFormSubmit(employeeForm.value)">
- <table>
- <tr>
- <td class="tbl1">
- <mat-form-field class="demo-full-width">
- <input formControlName="EmpName" matTooltip="Enter Employee Name" matInput placeholder="Employee Name">
- </mat-form-field>
- <mat-error>
- <span *ngIf="!employeeForm.get('EmpName').value && employeeForm.get('EmpName').touched"></span>
- </mat-error>
- </td>
- <td class="tbl1">
- <mat-form-field class="demo-full-width">
- <input matInput [matDatepicker]="picker"matTooltip="Enter Date Of Birth" formControlName="DateOfBirth"placeholder="Choose Date Of Birth">
- <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
- <mat-datepicker #picker></mat-datepicker>
- </mat-form-field>
- <mat-error>
- <span *ngIf="!employeeForm.get('DateOfBirth').value && employeeForm.get('DateOfBirth').touched"></span>
- </mat-error>
- </td>
- <td class="tbl1">
- <mat-form-field class="demo-full-width">
- <input formControlName="EmailId" matTooltip="Enter EmailId" matInput placeholder="EmailId">
- </mat-form-field>
- <mat-error>
- <span *ngIf="!employeeForm.get('EmailId').value && employeeForm.get('EmailId').touched"></span>
- </mat-error>
- </td>
- </tr>
- <tr>
- <td class="tbl1">
- <span>Gender</span>
- <br><br>
- <mat-radio-group matTooltip="Enter Gender"formControlName="Gender">
- <mat-radio-button value="0">Male</mat-radio-button>
- <mat-radio-button value="1">Female</mat-radio-button>
- </mat-radio-group>
- <mat-error>
- <span *ngIf="!employeeForm.get('Gender').value && employeeForm.get('Gender').touched"></span>
- </mat-error>
- </td>
- <td class="tbl1">
- <mat-form-field class="demo-full-width">
- <input matTooltip="Enter Address"formControlName="Address" matInput placeholder="Address">
- </mat-form-field>
- <mat-error>
- <span *ngIf="!employeeForm.get('Address').value && employeeForm.get('Address').touched"></span>
- </mat-error>
- </td>
- <td class="tbl1">
- <mat-form-field class="demo-full-width">
- <input formControlName="PinCode" matTooltip="Enter Pine Code" matInput placeholder="PinCode">
- </mat-form-field>
- <mat-error>
- <span *ngIf="!employeeForm.get('PinCode').value && employeeForm.get('PinCode').touched"></span>
- </mat-error>
- </td>
- </tr>
- <tr>
- <td></td>
- <td class="content-center">
- <button type="submit" mat-raised-button color="accent"matTooltip="Click Submit Button"[disabled]="!employeeForm.valid">Submit</button>
- <button type="reset" mat-raised-button color="accent"matTooltip="Click Reset Button" (click)="resetForm()">Reset</button>
- </td>
- <td>
- <p *ngIf="dataSaved" style="color:rgb(0, 128, 0);font-size:20px;font-weight:bold" Class="success" align="left">
- {{massage}}
- </p>
- </td>
- </tr>
- </table>
- <br><br>
- <table class="table" >
- <tr ngclass="btn-primary">
- <th class="tbl2">Employee Name</th>
- <th class="tbl2">Date Of Birth</th>
- <th class="tbl2">Email Id</th>
- <th class="tbl2">Gender</th>
- <th class="tbl2">Address</th>
- <th class="tbl2">Pine Code</th>
- <th class="tbl2">Edit</th>
- <th class="tbl2">Delete</th>
- </tr>
- <tr *ngFor="let employee of allEmployees | async">
- <td class="tbl2">{{employee.EmpName}}</td>
- <td class="tbl2">{{employee.DateOfBirth | date }}</td>
- <td class="tbl2">{{employee.EmailId}}</td>
- <td class="tbl2">{{employee.Gender ==0? 'Male' : 'Female'}}</td>
- <td class="tbl2">{{employee.Address}}</td>
- <td class="tbl2">{{employee.PinCode}}</td>
- <td class="tbl2">
- <button type="button" class="btn btn-info"matTooltip="Click Edit Button"(click)="loadEmployeeToEdit(employee.EmpId)">Edit</button>
- </td>
- <td class="tbl2">
- <button type="button" class="btn btn-danger"matTooltip="Click Delete Button"(click)="deleteEmployee(employee.EmpId)">Delete</button>
- </td>
- </tr>
- </table>
- </form>
- </mat-card-content>
- </mat-card>
- </div>
Step 9
Open app.component.html and write the below code.
- <p>
- <app-employee></app-employee>
- </p>
Step 10
Open employee.component.ts file and write the below code.
- import { Component, OnInit } from '@angular/core';
- import { FormBuilder, Validators } from '@angular/forms';
- import { Observable } from 'rxjs';
- import { EmployeeService } from '../employee.service';
- import { Employee } from '../employee';
- @Component({
- selector: 'app-employee',
- templateUrl: './employee.component.html',
- styleUrls: ['./employee.component.css']
- })
- export class EmployeeComponent implements OnInit {
- dataSaved = false;
- employeeForm: any;
- allEmployees: Observable<Employee[]>;
- employeeIdUpdate = null;
- massage = null;
- constructor(private formbulider: FormBuilder, private employeeService:EmployeeService) { }
- ngOnInit() {
- this.employeeForm = this.formbulider.group({
- EmpName: ['', [Validators.required]],
- DateOfBirth: ['', [Validators.required]],
- EmailId: ['', [Validators.required]],
- Gender: ['', [Validators.required]],
- Address: ['', [Validators.required]],
- PinCode: ['', [Validators.required]],
- });
- this.loadAllEmployees();
- }
- loadAllEmployees() {
- this.allEmployees = this.employeeService.getAllEmployee();
- }
- onFormSubmit() {
- this.dataSaved = false;
- const employee = this.employeeForm.value;
- this.CreateEmployee(employee);
- this.employeeForm.reset();
- }
- loadEmployeeToEdit(employeeId: string) {
- this.employeeService.getEmployeeById(employeeId).subscribe(employee=> {
- this.massage = null;
- this.dataSaved = false;
- this.employeeIdUpdate = employee.EmpId;
- this.employeeForm.controls['EmpName'].setValue(employee.EmpName);
- this.employeeForm.controls['DateOfBirth'].setValue(employee.DateOfBirth);
- this.employeeForm.controls['EmailId'].setValue(employee.EmailId);
- this.employeeForm.controls['Gender'].setValue(employee.Gender);
- this.employeeForm.controls['Address'].setValue(employee.Address);
- this.employeeForm.controls['PinCode'].setValue(employee.PinCode);
- });
- }
- CreateEmployee(employee: Employee) {
- if (this.employeeIdUpdate == null) {
- this.employeeService.createEmployee(employee).subscribe(
- () => {
- this.dataSaved = true;
- this.massage = 'Record saved Successfully';
- this.loadAllEmployees();
- this.employeeIdUpdate = null;
- this.employeeForm.reset();
- }
- );
- } else {
- employee.EmpId = this.employeeIdUpdate;
- this.employeeService.updateEmployee(employee).subscribe(() => {
- this.dataSaved = true;
- this.massage = 'Record Updated Successfully';
- this.loadAllEmployees();
- this.employeeIdUpdate = null;
- this.employeeForm.reset();
- });
- }
- }
- deleteEmployee(employeeId: string) {
- if (confirm("Are you sure you want to delete this ?")) {
- this.employeeService.deleteEmployeeById(employeeId).subscribe(() => {
- this.dataSaved = true;
- this.massage = 'Record Deleted Succefully';
- this.loadAllEmployees();
- this.employeeIdUpdate = null;
- this.employeeForm.reset();
- });
- }
- }
- resetForm() {
- this.employeeForm.reset();
- this.massage = null;
- this.dataSaved = false;
- }
- }
Step 11. Run
Open TERMINAL and write the following command to run the program.
ng serve -o
No comments:
Post a Comment