To create CRUD (Create, Read, Update, Delete) operations example application in Angular 17 using Web API; Simply set up angular application and then create services to handle HTTP CRUD web rest api requests and then create CRUD components and use web rest API through services to perform CRUD operations in angular applications.
In the latest version of Angular (18, 17) it has become very easy to call Web REST API using HTTP services and create CRUD operation example applications using HTTP services. In this guide, we will create a POSTS CRUD application, where you can create posts, edit posts, update posts, delete posts and list or display all posts using Web REST API.
How to Create CRUD Operations Application in Angular 17 with Web Rest API
Steps to create CRUD (Create, Read, Update, Delete) operations example application with a Web REST API in angular 17
Step 1 – Set Up New Angular Project
Simply open your cmd or terminal and run the ng new myCrudApp --no-standalone
command to install and create a new Angular project using Angular CLI:
ng new myCRUDApp --no-standalone cd myCRUDApp
Step 2 – Install Bootstrap 5
To install bootstrap 5 module in angular; simply run npm install bootstrap --save
command on cmd or terminal to install it;
npm install bootstrap --save
Navigate to the src directory and open style.css
, then add style in angular project;
/* You can add global styles to this file, and also import other style files */ @import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
Step 3 – Create a Routing Module for CRUD
To run the ng generate module post --routing
command on cmd or terminal window to create routing modules for crud component in angular:
ng generate module post --routing
Step 4 – Create Components For the CRUD Module
To generate CRUD operations components in application, Simply run the following command on cmd or terminal window:
ng generate component post/index ng generate component post/view ng generate component post/create ng generate component post/edit
Step 5 – Create Service to Handle HTTP Requests
To run the ng generate service post/post
command to create services, which is used to handle CRUD operations HTTP requests in angular application:
ng generate service post/post
Next open post.service.ts file from src/app/post/ directory and create HTTP requests in it like the following:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { Post } from './post'; @Injectable({ providedIn: 'root' }) export class PostService { private apiURL = "https://jsonplaceholder.typicode.com"; /*------------------------------------------ -------------------------------------------- Http Header Options -------------------------------------------- --------------------------------------------*/ httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } /*------------------------------------------ -------------------------------------------- Created constructor -------------------------------------------- --------------------------------------------*/ constructor(private httpClient: HttpClient) { } /** * Write code on Method * * @return response() */ getAll(): Observable<any> { return this.httpClient.get(this.apiURL + '/posts/') .pipe( catchError(this.errorHandler) ) } /** * Write code on Method * * @return response() */ create(post:Post): Observable<any> { return this.httpClient.post(this.apiURL + '/posts/', JSON.stringify(post), this.httpOptions) .pipe( catchError(this.errorHandler) ) } /** * Write code on Method * * @return response() */ find(id:number): Observable<any> { return this.httpClient.get(this.apiURL + '/posts/' + id) .pipe( catchError(this.errorHandler) ) } /** * Write code on Method * * @return response() */ update(id:number, post:Post): Observable<any> { return this.httpClient.put(this.apiURL + '/posts/' + id, JSON.stringify(post), this.httpOptions) .pipe( catchError(this.errorHandler) ) } /** * Write code on Method * * @return response() */ delete(id:number){ return this.httpClient.delete(this.apiURL + '/posts/' + id, this.httpOptions) .pipe( catchError(this.errorHandler) ) } /** * Write code on Method * * @return response() */ errorHandler(error:any) { let errorMessage = ''; if(error.error instanceof ErrorEvent) { errorMessage = error.error.message; } else { errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } return throwError(errorMessage); } }
To perform CRUD operations in Angular using PHP Laravel Web REST API, CodeIgniter Web REST API, or Node.js Express Web REST API, you can check out the tutorials below:
Step 6 – Create Interface Model
Run the ng generate interface post/post
command on cmd or terminal window to create an interface model:
ng generate interface post/post
Now, open post.model.ts
from the src/app
folder to define the post
interface like following into it:
export interface Post { id: number; title: string; body: string; }
Step 7 – Create Routes
Simply open post-routing.module.ts file from src/app/post/ directory and create routes into it like following:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { IndexComponent } from './index/index.component'; import { ViewComponent } from './view/view.component'; import { CreateComponent } from './create/create.component'; import { EditComponent } from './edit/edit.component'; const routes: Routes = [ { path: 'post', redirectTo: 'post/index', pathMatch: 'full'}, { path: 'post/index', component: IndexComponent }, { path: 'post/:postId/view', component: ViewComponent }, { path: 'post/create', component: CreateComponent }, { path: 'post/:postId/edit', component: EditComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class PostRoutingModule { }
Step 8 – Update the HTML template and Components
Now, simply create, edit, list and view components from src/app/post/ and update the HTML template and logic of the components to perform the crude operations.
Fetch the list of posts using web rest apis; Just open index.component.ts from src/app/post/index/ directory and call list showing web apis into it like the following:
import { Component, OnInit } from '@angular/core'; import { PostService } from '../post.service'; import { Post } from '../post'; @Component({ selector: 'app-index', templateUrl: './index.component.html', styleUrls: ['./index.component.css'] }) export class IndexComponent implements OnInit { posts: Post[] = []; /*------------------------------------------ -------------------------------------------- Created constructor -------------------------------------------- --------------------------------------------*/ constructor(public postService: PostService) { } /** * Write code on Method * * @return response() */ ngOnInit(): void { this.postService.getAll().subscribe((data: Post[])=>{ this.posts = data; console.log(this.posts); }) } /** * Write code on Method * * @return response() */ deletePost(id:number){ this.postService.delete(id).subscribe(res => { this.posts = this.posts.filter(item => item.id !== id); console.log('Post deleted successfully!'); }) } }
To update HTML template to show list with add, edit, and delete buttons, simply open the index.component.html
from src/app/post/index/ directory into it:
<div class="container"> <h1>Angular 17 CRUD Example with Web Rest Api - Tutsmake.com</h1> <a href="#" routerLink="/post/create/" class="btn btn-success">Create New Post</a> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Body</th> <th width="250px">Action</th> </tr> </thead> <tbody> <tr *ngFor="let post of posts"> <td>{{ post.id }}</td> <td>{{ post.title }}</td> <td>{{ post.body }}</td> <td> <a href="#" [routerLink]="['/post/', post.id, 'view']" class="btn btn-info">View</a> <a href="#" [routerLink]="['/post/', post.id, 'edit']" class="btn btn-primary">Edit</a> <button type="button" (click)="deletePost(post.id)" class="btn btn-danger">Delete</button> </td> </tr> </tbody> </table> </div>
To call create post api using http services; Simply navigate to src/app/post/create/ directory and open create.component.ts file and add the following code into it to call create post api service:
import { Component, OnInit } from '@angular/core'; import { PostService } from '../post.service'; import { Router } from '@angular/router'; import { FormGroup, FormControl, Validators} from '@angular/forms'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'] }) export class CreateComponent implements OnInit { form!: FormGroup; /*------------------------------------------ -------------------------------------------- Created constructor -------------------------------------------- --------------------------------------------*/ constructor( public postService: PostService, private router: Router ) { } /** * Write code on Method * * @return response() */ ngOnInit(): void { this.form = new FormGroup({ title: new FormControl('', [Validators.required]), body: new FormControl('', Validators.required) }); } /** * Write code on Method * * @return response() */ get f(){ return this.form.controls; } /** * Write code on Method * * @return response() */ submit(){ console.log(this.form.value); this.postService.create(this.form.value).subscribe((res:any) => { console.log('Post created successfully!'); this.router.navigateByUrl('post/index'); }) } }
To create a form for creating posts, simply create.component.html file from src/app/post/create/ directory and create it like following:
<div class="container"> <h1>Create New Post</h1> <a href="#" routerLink="/post/index" class="btn btn-primary">Back</a> <form [formGroup]="form" (ngSubmit)="submit()"> <div class="form-group"> <label for="title">Title:</label> <input formControlName="title" id="title" type="text" class="form-control"> <div *ngIf="f['title'].touched && f['title'].invalid" class="alert alert-danger"> <div *ngIf="f['title'].errors && f['title'].errors['required']">Title is required.</div> </div> </div> <div class="form-group"> <label for="body">Body</label> <textarea formControlName="body" id="body" type="text" class="form-control"> </textarea> <div *ngIf="f['body'].touched && f['body'].invalid" class="alert alert-danger"> <div *ngIf="f['body'].errors && f['body'].errors['required']">Body is required.</div> </div> </div> <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button> </form> </div>
To create call edit posts apis; simply open edit.component.ts file from src/app/post/edit/ directory and call it like following:
import { Component, OnInit } from '@angular/core'; import { PostService } from '../post.service'; import { ActivatedRoute, Router } from '@angular/router'; import { Post } from '../post'; import { FormGroup, FormControl, Validators} from '@angular/forms'; @Component({ selector: 'app-edit', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'] }) export class EditComponent implements OnInit { id!: number; post!: Post; form!: FormGroup; /*------------------------------------------ -------------------------------------------- Created constructor -------------------------------------------- --------------------------------------------*/ constructor( public postService: PostService, private route: ActivatedRoute, private router: Router ) { } /** * Write code on Method * * @return response() */ ngOnInit(): void { this.id = this.route.snapshot.params['postId']; this.postService.find(this.id).subscribe((data: Post)=>{ this.post = data; }); this.form = new FormGroup({ title: new FormControl('', [Validators.required]), body: new FormControl('', Validators.required) }); } /** * Write code on Method * * @return response() */ get f(){ return this.form.controls; } /** * Write code on Method * * @return response() */ submit(){ console.log(this.form.value); this.postService.update(this.id, this.form.value).subscribe((res:any) => { console.log('Post updated successfully!'); this.router.navigateByUrl('post/index'); }) } }
To create update post form; simply open edit.component.html file from src/app/post/edit/ directory and create update post form like following:
<div class="container"> <h1>Update Post</h1> <a href="#" routerLink="/post/index" class="btn btn-primary">Back</a> <form [formGroup]="form" (ngSubmit)="submit()"> <div class="form-group"> <label for="title">Title:</label> <input formControlName="title" id="title" type="text" [(ngModel)]="post.title" class="form-control"> <div *ngIf="f['title'].touched && f['title'].invalid" class="alert alert-danger"> <div *ngIf="f['title'].errors && f['title'].errors['required']">Title is required.</div> </div> </div> <div class="form-group"> <label for="body">Body</label> <textarea formControlName="body" id="body" type="text" [(ngModel)]="post.body" class="form-control"> </textarea> <div *ngIf="f['body'].touched && f['body'].invalid" class="alert alert-danger"> <div *ngIf="f['body'].errors && f['body'].errors['required']">Body is required.</div> </div> </div> <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Update</button> </form> </div>
To open the app.component.html
file and add router outlet like following into it;
<router-outlet></router-outlet>
Step 9 – Import Modules
Simply open app.module.ts
file and import the required modules, components, and services like following into it:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { PostModule } from './post/post.module'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, PostModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Next, simply open post.module.ts file inside src/app/post/ folder and import modules in it like following:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { PostRoutingModule } from './post-routing.module'; import { IndexComponent } from './index/index.component'; import { ViewComponent } from './view/view.component'; import { CreateComponent } from './create/create.component'; import { EditComponent } from './edit/edit.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [IndexComponent, ViewComponent, CreateComponent, EditComponent], imports: [ CommonModule, PostRoutingModule, FormsModule, ReactiveFormsModule ] }) export class PostModule { }
Step 10 – Run Angular Application
Run ng server
command on cmd or termianl window to start the Angular development server:
ng serve
Open your browser and navigate to http://localhost:4200/post/index
. You should see your Angular CRUD operations application example with web rest api.
Conclusion
We hope that with the help of the tutorial guide, you have learned how to create CRUD operations example application in your Angular 17 application using Web REST API and HTTP services.