Introduction
Angular 4 is more popular nowadays and for beginners, I will tell you what’s new in Angular 4 and show you a practical example of Angular 4 with ASP.NET Web API for inserting, deleting and displaying data using Angular 4.
Basically, this article will demonstrate with example the following:
- Step by step procedure to create ASP.NET Web API project
- Prerequisites and Setup for Angular 4
- How to create Angular 4 Application and install Angular 4 packages
- How to create service and component in Angular 4
- How to get data from server side (Web API)
- How to bind/Load/Fill data from Server side to HTML page using Angular 4
- How to perform insert, edit, update and delete operation on view using Angular 4 data binding
What is Angular
Angular is an Open Source which is developed by Google.
Angular 4 is the latest version of Angular. It is a front-end web application platform.
What’s New in Angular 4
- Reduced Size and Improved Performance
- Separate Animation Package
ngIf
with else
: We can use an else
syntax in your templates As
: Introduced as new
keyword, As Keywprd
allows to store a result in a variable of the template, to use it in the element Titlecase
: Angular 4 introduced a new titlecase
pipe. This pipe converts the first letter of each word into uppercase Http
: Adding search parameters to an HTTP request has been simplified Validators
: Added new validators like required
, minLength
, maxLength
and pattern
. Email validator helps you validate that the input is a valid email
What You Need
- Basic knowledge of Angular
- Angular CLI
Prerequisites
- Node
- Npm
- Angular CLI
- Typescript
- Text editor- visual code
Install the below setup step by step, Using Visual Studio Code or Command Prompt
- Node
- Npm
- Angular CLI
- Typescript
- Visual code
Set Up for Angular 4
Verify Version of Node
Installing Angular CLI
npm install -g @angular/cli
Typescript Installation
First, check typescript version using the below command:
tsc –version
If Typescript is not installed, then use command:
npm install –g typescript
Step 1: Start With ASP.NET Web API
- Create Database
WebAPIDB
with the below structure:
CREATE TABLE [dbo].[Employee] (
[EmployeeID] INT IDENTITY (1, 1) NOT NULL,
[FirstName] VARCHAR (50) NULL,
[LastName] VARCHAR (50) NULL,
[EmpCode] VARCHAR (50) NULL,
[Position] VARCHAR (50) NULL,
[Office] VARCHAR (50) NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([EmployeeID] ASC)
);
- Generate Entity Model from Database Name as DBModel.edmx:
- Add Web API Controller:
public class EmployeeController : ApiController
{
private MyDBEntities db = new MyDBEntities();
public IQueryable<Employee> GetEmployees()
{
return db.Employees;
}
public IHttpActionResult PutEmployee(int id, Employee employee)
{
if (id != employee.EmployeeID)
{
return BadRequest();
}
db.Entry(employee).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
[ResponseType(typeof(Employee))]
public IHttpActionResult PostEmployee(Employee employee)
{
db.Employees.Add(employee);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
}
[ResponseType(typeof(Employee))]
public IHttpActionResult DeleteEmployee(int id)
{
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return NotFound();
}
db.Employees.Remove(employee);
db.SaveChanges();
return Ok(employee);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool EmployeeExists(int id)
{
return db.Employees.Count(e => e.EmployeeID == id) > 0;
}
}
In the above class, we have the following methods:
GetEmployee()
method will return all the employees in JSON format PostEmployee()
method will add a new employee
to the database DeleteEmployee()
method will delete existing employee
- Install Swagger Package Swashbuckle
Test Web API using Swagger:
Step 2: Start With Angular 4
Step 1
Create a folder of the name EmployeeApplication. Open Visual Studio code and open this folder in it. This folder will be used as the workspace for creating all the required files for the application.
Creating new Angular projects is easy by using Angular CLI in the following way:
Go To View -- > Integrated Terminal
Cd EmployeeApplication
$ ng new EmployeeApplication
Run the following command from the command prompt.
npm install
To serve the app locally, inside your newly created project, run the following command:
ng serve
Open Chrome and add address http://localhost:4200/
Create New Employee Service using the below command:
ng generate service Employee
EmployeeService.js file is used for calling server-side code by using .$http
in EmployeeService.js file we have created an Angular service called as EmployeeService
. To call Web API EmployeeControllers
for insert
, update
, delete
function, we have created three functions in EmployeeService.js.
We have created the following method in service to call Server Side code:
postEmployee()
: This will post data to server getEmployeeList()
: This will fetch data from server deleteEmployee()
: This will delete employee from server
export class EmployeeService {
selectedEmployee : Employee;
employeeList : Employee[];
constructor(private http : Http) { }
postEmployee(emp : Employee){
var body = JSON.stringify(emp);
var headerOptions = new Headers({'Content-Type':'application/json'});
var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
return this.http.post('http://localhost:28750/api/Employee',body,requestOptions).map(x => x.json());
}
putEmployee(id, emp) {
var body = JSON.stringify(emp);
var headerOptions = new Headers({ 'Content-Type': 'application/json' });
var requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
return this.http.put('http://localhost:28750/api/Employee/' + id,
body,
requestOptions).map(res => res.json());
}
getEmployeeList(){
this.http.get('http://localhost:28750/api/Employee')
.map((data : Response) =>{
return data.json() as Employee[];
}).toPromise().then(x => {
this.employeeList = x;
})
}
deleteEmployee(id: number) {
return this.http.delete('http://localhost:28750/api/Employee/' + id).map(res => res.json());
}
}
A component in Angular:
A major part of the development with Angular 4 is done in the components.
In Angular application, Components are basically classes that interact with the .html file of the component.
It consists of:
- Template
- Class
- Metadata
We will get all details of the component using the below link:
Create New Employee Component using the below command:
ng generate component Employee
export class EmployeeComponent implements OnInit {
constructor(private employeeService: EmployeeService, private toastr: ToastrService) { }
ngOnInit() {
this.resetForm();
}
resetForm(form?: NgForm) {
if (form != null)
form.reset();
this.employeeService.selectedEmployee = {
EmployeeID: null,
FirstName: '',
LastName: '',
EmpCode: '',
Position: '',
Office: ''
}
}
onSubmit(form: NgForm) {
if (form.value.EmployeeID == null) {
this.employeeService.postEmployee(form.value)
.subscribe(data => {
this.resetForm(form);
this.employeeService.getEmployeeList();
this.toastr.success('New Record Added Successfully', 'Employee Register');
})
}
else {
this.employeeService.putEmployee(form.value.EmployeeID, form.value)
.subscribe(data => {
this.resetForm(form);
this.employeeService.getEmployeeList();
this.toastr.info('Record Updated Successfully!', 'Employee Register');
});
}
}
}
Add another component for List
:
ng generate component EmployeeList
We are using ToasterService
for showing notification on UI.
This component is used for showing employing list. It will fetch data from Web API and will show on UI.
export class EmployeeListComponent implements OnInit {
constructor(private employeeService: EmployeeService,private toastr : ToastrService) { }
ngOnInit() {
this.employeeService.getEmployeeList();
}
showForEdit(emp: Employee) {
this.employeeService.selectedEmployee = Object.assign({}, emp);;
}
onDelete(id: number) {
if (confirm('Are you sure to delete this record ?') == true) {
this.employeeService.deleteEmployee(id)
.subscribe(x => {
this.employeeService.getEmployeeList();
this.toastr.warning("Deleted Successfully","Employee Register");
})
}
}
}
We are using the below attributes:
- The
ng-model
attribute is used for Binding controls such as input, text area and selects in the view into the model ng-submit
: The ng-submit
directive submits a form to a specified function ngModel
: The ng-model
attribute is used to bind the data in your model to the view presented to the user.
Add the below UI to employee.component.html file:
<form class="emp-form"
#employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
<input type="hidden" name="EmployeeID" #EmployeeID="ngModel"
[(ngModel)]="employeeService.selectedEmployee.EmployeeID">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" name="FirstName" #FirstName="ngModel"
[(ngModel)]="employeeService.selectedEmployee.FirstName"
placeholder="First Name" required>
<div class="validation-error" *ngIf="FirstName.invalid && FirstName.touched">
This Field is Required.</div>
</div>
<div class="form-group col-md-6">
<input class="form-control" name="LastName" #LastName="ngModel"
[(ngModel)]="employeeService.selectedEmployee.LastName" placeholder="Last Name"
required>
<div class="validation-error" *ngIf="LastName.invalid && LastName.touched">
This Field is Required.</div>
</div>
</div>
<div class="form-group">
<input class="form-control" name="Position" #Position="ngModel"
[(ngModel)]="employeeService.selectedEmployee.Position" placeholder="Position">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" name="EmpCode" #EmpCode="ngModel"
[(ngModel)]="employeeService.selectedEmployee.EmpCode" placeholder="Emp Code">
</div>
<div class="form-group col-md-6">
<input class="form-control" name="Office" #Office="ngModel"
[(ngModel)]="employeeService.selectedEmployee.Office" placeholder="Office">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<button [disabled]="!employeeForm.valid"
type="submit" class="btn btn-lg btn-block btn-info">
<i class="fa fa-floppy-o"></i> Submit</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block btn-secondary"
(click)="resetForm(employeeForm)">
<i class="fa fa-repeat"></i> Reset</button>
</div>
</div>
</form>
Add command Ng Serve
to test your application.
NPM Start
Open Chrome and add address http://localhost:4200/
By using this, you have successfully inserted data in the database and you have also shown this in the gridview
. Click on submit.
Please take a look at the attached code for more information.
Happy programming!!
Don’t forget to leave your feedback and comments below!