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.
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 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.
☑️ 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/
note: ng serve command launches the server, watches your files for changes, and rebuilds the app as you save changes
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. }
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; } }
☑️ 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
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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork