Angular Setup and CRUD Operations: A Comprehensive Guide

Introduction

In the document, I will be covering Angular installation and setup a new project and will be creating some functionality. For the basic understanding of Angular, I will be explaining about components, services and API calls. Will be creating CRUD operations for the employee System. Adding new employees, listing all employees and deleting employees.

Prerequisites

No need for any prior knowledge of Angular, this will cover a basic understanding of Angular. Only need for basic understanding of HTML, CSS, and js. And should know how the front-end works.

Angular

Angular is a modern MVVC framework and platform that is used to build enterprise Single-page web applications (or SPAs) using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps. Angular is an opinionated framework which means that it specifies a certain style and certain rules that developers need to follow and adhere to while developing apps with Angular, therefore you need to learn Angular and the various components that make up an Angular app.

Installation

☑️ Step: 1- Install Node.js

Install Node js from this website, and follow the basic next-next steps. After downloading Node.js, the node package manager (npm) should automatically be installed. Test it out by doing:

$ npm --version

Related read: Building RESTful APIs with Node.js and Angular

☑️ Step: 2– Install Angular CLI

Install Angular using npm in the terminal.

$ npm install -g @angular/cli

☑️ Step: 3 – Navigate to the project directory

$ cd ~/Dev/
$ mkdir appDir && cd appDir 
$ ng new cfe-app

ng new takes a minute to run.

☑️ Step: 4 – Navigate to the project & run the local server

Navigate to directory

$ cd /path/to/your/newly/created/app/

This will automatically open http://localhost:4200/

angular demo app interface

note: ng serve command launches the server, watches your files for changes, and rebuilds the app as you save changes

Components

Components are the building blocks that compose an application. A component includes a TypeScript class with a @Component() decorator, an HTML template, and styles. The @Component() decorator specifies the following Angular-specific information:

🔸 A CSS selector that defines how the component is used in a template. HTML elements in your template that match this selector become instances of the component.

🔸 An HTML template that instructs Angular how to render the component

🔸 An optional set of CSS styles that define the appearance of the template’s HTML elements

The following is a minimal Angular component.

import { Component } from '@angular/core';

@Component({
selector: 'hello-world',
template: `
<h2>Hello World</h2>
<p>This is my first component!</p>
`
})
export class HelloWorldComponent {
// The code in this class drives the component's behavior.
}

Services

Angular services are singleton objects that get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e. data does not get refreshed and is available all the time. The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application.

An example of when to use services would be to transfer data from one controller to another custom service.

Services can depend on other services. For example, here’s a HeroService that depends on the Logger service, and also uses BackendService to get heroes. That service in turn might depend on the HttpClient service to fetch heroes asynchronously from a server.

export class HeroService {
private heroes: Hero[] = [];

constructor(
private backend: BackendService,
private logger: Logger) { }

getHeroes() {
this.backend.getAll(Hero).then( (heroes: Hero[]) => {
this.logger.log(`Fetched ${heroes.length} heroes.`);
this.heroes.push(...heroes); // fill cache
});
return this.heroes;
}
}

Unlock the Potential of AngularJS: Hire An Expert AngularJS Developer

Steps to Make API calls

☑️ Step: 1

we’ll proceed to set up the HttpClient module in our example.

HttpClient lives in a separate Angular module, so we’ll need to import it in our main application module before we can use it.

Open your example project with a code editor or IDE. I’ll be using Visual Studio Code.

Next, open the src/app/app.module.ts file, import HttpClientModule and add it to the imports array of the module as follows:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

☑️ Step: 2

In this step, we’ll proceed to create the Angular components that control our application UI.

Head back to a new command-line interface and run the following command:

$ cd ~/angular-httpclient-example
$ ng generate component home

This is the output of the command:

CREATE src/app/home/home.component.html (19 bytes)
CREATE src/app/home/home.component.spec.ts (614 bytes)
CREATE src/app/home/home.component.ts (261 bytes)
CREATE src/app/home/home.component.css (0 bytes)
UPDATE src/app/app.module.ts (467 bytes)

The CLI created four files for the component and added them to the declarations array in the src/app/app.module.ts file.

Next, let’s create the about component using the following command:

☑️ Step: 3

Next, open the src/app/home/home.component.html and add the following code:

<div>
<app-navbar></app-navbar>
<div class="p-5">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Email</th>
<th scope="col">Address</th>
<th scope="col">Address2</th>
<th scope="col">City</th>
<th scope="col">State</th>
<th scope="col">Zipcode</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let emp of employees; index as i">
<th scope="row">{{i + 1}}</th>
<td>{{emp.first_name}}</td>
<td>{{emp.last_name}}</td>
<td>{{emp.email}}</td>
<td>{{emp.address}}</td>
<td>{{emp.address2}}</td>
<td>{{emp.city}}</td>
<td>{{emp.state}}</td>
<td>{{emp.zipcode}}</td>
<td><button type="button" class="btn btn-danger" (click)="onDelete(emp)">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</div>

☑️ Step: 4

In this step, we’ll proceed to add routing to our example.

Head back to the src/app/app-routing.module.ts file, which was automatically created by Angular CLI for routing configuration, and import the components then add the routes as follows:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddEmpComponent } from './pages/add-emp/add-emp.component';
import { HomeComponent } from './pages/home/home.component';

const routes: Routes = [
{path: 'add-emp', component: AddEmpComponent},
{path: '', component: HomeComponent},
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

We first imported the home and about components, next, we added three routes including a route for redirecting the empty path to the home component, so when the user visits the app, they will be redirected to the home page.

☑️ Step: 5

Now, let’s generate an Angular service that interfaces with the JSON REST API. Head back to your command-line interface and run the following command:

$ ng generate service data

Next, open the src/app/data.service.ts file, import and inject HttpClient as follows:

import { Injectable } from '@angular/core';
import { getEmpoyeeURL } from 'src/app/utils/api-urls';
import { HttpClient } from '@angular/common/http';
import { IEmployee } from 'src/app/models/employee';
import { Observable } from 'rxjs';


@Injectable({
providedIn: 'root'
})
export class GetEmpService {

private _url: string = getEmpoyeeURL;

constructor(private http: HttpClient) { }

getEmployees(): Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this._url);
}
}

The method simply invokes the get() method of HttpClient to send GET requests to the REST API server.

Next, we now need to use this service in our home component. Open the src/app/home/home.component.ts file, import and inject the data service as follows:

import { Component } from '@angular/core';
import { IEmployee } from 'src/app/models/employee';
import { GetEmpService } from 'src/app/services/get_emp/get-emp.service';
import { DeleteEmpService } from 'src/app/services/delete_emp/delete-emp.service';
import { ToastersService } from 'src/app/services/notifications/toasters.service';
import {Router} from '@angular/router';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
public employees: IEmployee[] = []

constructor(
private _getGmployeeService: GetEmpService,
private _deleteEmployeeService: DeleteEmpService,
private _toasterService: ToastersService,
private router: Router
) {}

ngOnInit() {
this._getGmployeeService.getEmployees().subscribe(data => this.employees = data);
}

onDelete(emp: any) {
this._deleteEmployeeService.deleteEmployees(emp.id).subscribe(
data => this.showResponsePopup(data, false),
error => this.showResponsePopup(error, true)
);
}

showResponsePopup(response: any, isError: boolean){

if(isError){
console.log(response.error);
const title: string = Object.keys(response.error)[0];
const msg: string = Object.values(response.error)[0] as string;
this._toasterService.showError(msg, title);
}
else{
this._toasterService.showSuccess("successfully delete", "Employee");
this._getGmployeeService.getEmployees().subscribe(data => this.employees = data);
}
}
}

Finally, the result will look like the image shown below

employee-system-results

coma

Conclusion

In conclusion, this blog provides a comprehensive guide to setting up Angular and implementing CRUD (Create, Read, Update, Delete) operations in an Employee System. The blog covers the installation process of Node.js and Angular CLI, explains the basic concepts of Angular such as components and services, and demonstrates how to make API calls using the HttpClient module.

In this document, we have written code to get the employees list and show the data in the UI. I have already written the whole CRUD system code and uploaded it to my GitHub account and I will share a link for you to go through it.

Refer my GitHub Repo

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?