Angular 12 CRUD Operation Application with Web API

Angular 12 crud operation example. In this tutorial i am going to show you how to create crud app in angular 12 with web api.

CRUD stands for “Create, Read, Update, and Delete,” which are the four basic database operations. Many HTTP services also model CRUD operations through REST or REST-like APIs. In this tutorial, you will build a very simple web API to manage a list of products.

Angular 12 Crud Operation Application Example with Web APIs

  • Step 1 – Create New Angular 12 App
  • Step 2 – Install Bootstrap
  • Step 3 – Create Module & Routing
  • Step 4 – Create Component For Module
  • Step 5 – Adding Routes
  • Step 6 – Create Interface
  • Step 7 – Create Services
  • Step 8 – Add Code in Component and Template
  • Step 9 – Import to Modules
  • Step 10 – Start Angular App

Step 1 – Create New Angular 12 App

Open your terminal and execute the following command on it to install angular app:

ng new my-crud-app --routing

Step 2 – Install Bootstrap

Execute the following command on terminal to install boostratp:

npm install bootstrap --save

After that, import this css file into angular 12 crud app:

src/styles.css

/* You can add global styles to this file, and also import other style files */@import "~bootstrap/dist/css/bootstrap.css";

Step 3 – Create Module & Routing

Execute the following command on terminal to create module in angular 12 app:

ng generate module post --routing

The above given command will create files in the following locations:

src/app/post/post.module.ts
src/app/post/post-routing.module.ts

Step 4 – Create Component For Module

Execute the following commands on terminal to create components in angular app:

ng generate component post/index
ng generate component post/view
ng generate component post/create
ng generate component post/edit

Now, you can see that, the above commands will create some component files into the following locations:

src/app/post/index/*
src/app/post/view/*
src/app/post/create/*
src/app/post/edit/*

Step 5 – Adding Routes

Go to src/app/post directory and open post-routing.module.ts Then add the routes into post-routing.module.ts file:

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 6 – Create Interface

Execute the following command on terminal to create interface:

ng generate interface post/post

Then visit src/app/post directory and open post.ts. And add the following code into it:

export interface Post {
id: number;
title: string;
body: string;
}

Step 7 – Create Services

Execute the following command to create services:

ng generate service post/post

After that, visit src/app/post directory and open post.service.ts. Then add the following code into it:

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";
   
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }
  
  constructor(private httpClient: HttpClient) { }
   
  getAll(): Observable<Post[]> {
    return this.httpClient.get<Post[]>(this.apiURL + '/posts/')
    .pipe(
      catchError(this.errorHandler)
    )
  }
   
  create(post): Observable<Post> {
    return this.httpClient.post<Post>(this.apiURL + '/posts/', JSON.stringify(post), this.httpOptions)
    .pipe(
      catchError(this.errorHandler)
    )
  }  
   
  find(id): Observable<Post> {
    return this.httpClient.get<Post>(this.apiURL + '/posts/' + id)
    .pipe(
      catchError(this.errorHandler)
    )
  }
   
  update(id, post): Observable<Post> {
    return this.httpClient.put<Post>(this.apiURL + '/posts/' + id, JSON.stringify(post), this.httpOptions)
    .pipe(
      catchError(this.errorHandler)
    )
  }
   
  delete(id){
    return this.httpClient.delete<Post>(this.apiURL + '/posts/' + id, this.httpOptions)
    .pipe(
      catchError(this.errorHandler)
    )
  }
    
  
  errorHandler(error) {
    let errorMessage = '';
    if(error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    return throwError(errorMessage);
 }
}

Note that,this example will use https://jsonplaceholder.typicode.com web site api.

Step 8 – Add Code in Component and Template

Create components and template like list page, create page, edit page and view page in angular crud app.

1) List Page Template and Component

First of all, visit src/app/post/index directory and open index.component.ts or create index.components.ts, if not exist. Then add the following code into it:

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[] = [];
  
  constructor(public postService: PostService) { }
  
  ngOnInit(): void {
    this.postService.getAll().subscribe((data: Post[])=>{
      this.posts = data;
      console.log(this.posts);
    })  
  }
  
  deletePost(id){
    this.postService.delete(id).subscribe(res => {
         this.posts = this.posts.filter(item => item.id !== id);
         console.log('Post deleted successfully!');
    })
  }
  
}

Now, visit src/app/post/index directory and open index.component.html or create index.component.html, if not exist. Then add the following code into it:

<div class="container">
    <h1>angular 12 crud example with web api - Laratutorials.com</h1>
  
    <a href="#" routerLink="/post/create/" class="btn btn-success">Create New Post</a>
    
    <table class="table table-bordered">
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Body</th>
        <th width="220px">Action</th>
      </tr>
      <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>
    </table>
 </div>

2) Add Post Page Template and Component

First of all, visit src/app/post/create directory and open create.component.ts or create create.components.ts, if not exist. Then add the following code into it:

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;
   
  constructor(
    public postService: PostService,
    private router: Router
  ) { }
  
  ngOnInit(): void {
    this.form = new FormGroup({
      title: new FormControl('', [Validators.required]),
      body: new FormControl('', Validators.required)
    });
  }
   
  get f(){
    return this.form.controls;
  }
    
  submit(){
    console.log(this.form.value);
    this.postService.create(this.form.value).subscribe(res => {
         console.log('Post created successfully!');
         this.router.navigateByUrl('post/index');
    })
  }
  
}

Now, visit src/app/post/create a directory and open create.component.html or create create.component.html, if not exist. Then add the following code into it:

<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.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.required">Body is required.</div>
            </div>
        </div>
  
        <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>
    </form>
</div>

3) Edit Page Template and Component

First of all, visit src/app/post/edit directory and open edit.component.ts or create edit.components.ts, if not exist. Then add the following code into it:

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;
  
  constructor(
    public postService: PostService,
    private route: ActivatedRoute,
    private router: Router
  ) { }
  
  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)
    });
  }
   
  get f(){
    return this.form.controls;
  }
     
  submit(){
    console.log(this.form.value);
    this.postService.update(this.id, this.form.value).subscribe(res => {
         console.log('Post updated successfully!');
         this.router.navigateByUrl('post/index');
    })
  }
   
}

Now, visit src/app/post/edit a directory and open edit.component.html or create edit.component.html, if not exist. Then add the following code into it:

<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.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.required">Body is required.</div>
            </div>
        </div>
        
        <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Update</button>
    </form>
</div>

4) Detail Page Template and Component

First of all, visit src/app/post/view directory and open view.component.ts or view.components.ts, if not exist. Then add the following code into it:

import { Component, OnInit } from '@angular/core';
import { PostService } from '../post.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Post } from '../post';
  
@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {
   
  id: number;
  post: Post;
   
  constructor(
    public postService: PostService,
    private route: ActivatedRoute,
    private router: Router
   ) { }
  
  ngOnInit(): void {
    this.id = this.route.snapshot.params['postId'];
      
    this.postService.find(this.id).subscribe((data: Post)=>{
      this.post = data;
    });
  }
  
}

Now, visit src/app/post/view a directory and open view.component.html or create view.component.html, if not exist. Then add the following code into it:

<div class="container">
    <h1>View Post</h1>
  
    <a href="#" routerLink="/post/index" class="btn btn-primary">Back</a>
   
    <div>
        <strong>ID:</strong>
        <p>{{ post.id }}</p>
    </div>
   
    <div>
        <strong>Title:</strong>
        <p>{{ post.title }}</p>
    </div>
   
    <div>
        <strong>Body:</strong>
        <p>{{ post.body }}</p>
    </div>
   
</div>

Now, visit src/app directory and open app.component.html. Then add the following line into it:

<router-outlet></router-outlet>

Step 9 – Import to Modules

In this step, Now, visit src/app directory and open app.module.ts. Then add the following line 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 { }

And visit src/app/post directory and open post.module.ts. Then add the following line into it:

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 – Start Angular App

In this step, execute the following command on terminal to start angular app:

ng serve

Then open your browser and hit the following url on it:

localhost:4200/post

One Comment

  1. mahen said:

    nice, thank you so much, for more than 3+ years I was subscribed to your website. Thank you for sharing your knowledge

    December 30, 2020
    Reply

Leave a Reply

Your email address will not be published.