Friday, November 22, 2024
Google search engine
HomeLanguagesAngularCrud Operations in Angular 16 using Web REST API Example Tutorial

Crud Operations in Angular 16 using Web REST API Example Tutorial

Angular 16 is the latest version of the popular front-end framework, and it brings significant improvements and enhancements over its previous versions. Using Angular 16, the latest version of the popular front-end framework, to create a user management application that interacts with a simple JSON server as our Web REST API. You will learn how to set up the Angular 16 project, implement the CRUD (Create, Read, Update, Delete) operations, and connect to the Web REST API for data retrieval and manipulation.

Angular 16 Crud Operations Example with Web Rest API Tutorial

Steps to implement the Angular 16 CRUD (Create, Read, Update, Delete) operations application with a Web REST API for data retrieval and manipulation:

  • Step 1 – Set Up the Angular 16 Project
  • Step 2 – Install Bootstrap 5
  • Step 3 – Set Up the Web REST API
  • Step 4 – Create Angular Components and Services
  • Step 5 – Implement CRUD Operations
  • Step 6 – Create User Model
  • Step 7 – Configure Routing
  • Step 8 – Implement User List Component
  • Step 9 – Implement User Create Component
  • Step 10 – Implement User Edit Component
  • Step 11 – Update App Component & Module.ts
  • Step 12 – Run Angular Application

Step 1 – Set Up the Angular 16 Project

First of all, open your cmd or command prompt and execute the following command into it to install and create a new Angular 16 project using Angular CLI:

ng new my-crud-app --routing
ng new angular-crud-app
cd angular-crud-app

Step 2 – Install Bootstrap 5

Next, you need to execute the following command on cmd to install bootstrap 5 in your angular project:

npm install bootstrap --save

After that, import this css file into angular 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 – Set Up the Web REST API

Next, You need to install JSON server globally for your web REST API, so for that execute following command on cmd:

npm install -g json-server

Once you have done above things, now create a JSON file (e.g., db.json) in the root of your project and define sample data for your CRUD operations:

{
  "users": [
    { "id": 1, "name": "John Doe", "email": "[email protected]" },
    { "id": 2, "name": "Jane Smith", "email": "[email protected]" }
  ]
}

And execute the following command on cmd to start the JSON server using the db.json file:

json-server --watch db.json

If you want to perform CRUD operations in Angular using PHP Laravel web REST APIs, CodeIgniter web REST APIs, or Node.js Express web REST APIs, then for this, you can see the tutorials given below:

Step 4 – Create Angular Components and Services

Next, you need to create a new Angular service to interact with Web Rest API, so type the following command on cmd:

ng generate service user

Then execute the following command on cmd to generate four components for the CRUD operations:

ng generate component user-list
ng generate component user-create
ng generate component user-edit
ng generate component user-details

Step 5 – Implement CRUD Operations

Next, open the user.service.ts file, implement methods to perform CRUD operations using Angular’s HttpClient module. like following:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user.model';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = 'http://localhost:3000/users';

  constructor(private http: HttpClient) { }

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.apiUrl);
  }

  getUser(id: number): Observable<User> {
    return this.http.get<User>(`${this.apiUrl}/${id}`);
  }

  createUser(user: User): Observable<User> {
    return this.http.post<User>(this.apiUrl, user);
  }

  updateUser(user: User): Observable<User> {
    return this.http.put<User>(`${this.apiUrl}/${user.id}`, user);
  }

  deleteUser(id: number): Observable<any> {
    return this.http.delete<any>(`${this.apiUrl}/${id}`);
  }
}

Note that:- Implement the CRUD operations in the respective components (user-list, user-create, user-edit, user-details) using the service methods.

Step 6 – Create User Model

Create a new file user.model.ts inside the src/app folder to define the User interface:

export interface User {
  id: number;
  name: string;
  email: string;
}

Step 7 – Configure Routing

Open the app-routing.module.ts file and define the routes to routing in the angular app for each component:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserListComponent } from './user-list/user-list.component';
import { UserCreateComponent } from './user-create/user-create.component';
import { UserEditComponent } from './user-edit/user-edit.component';

const routes: Routes = [
  { path: '', redirectTo: '/users', pathMatch: 'full' },
  { path: 'users', component: UserListComponent },
  { path: 'users/create', component: UserCreateComponent },
  { path: 'users/edit/:id', component: UserEditComponent },
];

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

Step 8 – Implement User List Component

Open the user-list.component.ts file, add the following code to list all users and implement the delete functionality:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';
import { User } from '../user.model';

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styleUrls: ['./user-list.component.css']
})
export class UserListComponent implements OnInit {
  users: User[];

  constructor(private userService: UserService) { }

  ngOnInit(): void {
    this.loadUsers();
  }

  loadUsers(): void {
    this.userService.getUsers()
      .subscribe(users => this.users = users);
  }

  deleteUser(id: number): void {
    this.userService.deleteUser(id)
      .subscribe(() => {
        this.loadUsers();
      });
  }
}

Create the template file user-list.component.html to display the list of users and enable delete functionality:

<div *ngFor="let user of users">
  <p>{{ user.name }} ({{ user.email }}) <button (click)="deleteUser(user.id)">Delete</button></p>
</div>

Step 9 – Implement User Create Component

Open the user-create.component.ts file, add the following code to create a new user:

import { Component } from '@angular/core';
import { UserService } from '../user.service';
import { User } from '../user.model';

@Component({
  selector: 'app-user-create',
  templateUrl: './user-create.component.html',
  styleUrls: ['./user-create.component.css']
})
export class UserCreateComponent {
  newUser: User = {
    id: 0,
    name: '',
    email: ''
  };

  constructor(private userService: UserService) { }

  createUser(): void {
    this.userService.createUser(this.newUser)
      .subscribe(() => {
        // Handle success and navigation, if needed
      });
  }
}

Next, Create the template file user-create.component.html to provide a form for creating a new user:

<form>
  <label>Name:</label>
  <input type="text" [(ngModel)]="newUser.name" name="name">
  <label>Email:</label>
  <input type="text" [(ngModel)]="newUser.email" name="email">
  <button (click)="createUser()">Create User</button>
</form>

Step 10 – Implement User Edit Component

Open the user-edit.component.ts file, add the following code to edit an existing user:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { UserService } from '../user.service';
import { User } from '../user.model';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.css']
})
export class UserEditComponent implements OnInit {
  user: User;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private userService: UserService
  ) { }

  ngOnInit(): void {
    this.getUser();
  }

  getUser(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    this.userService.getUser(id)
      .subscribe(user => this.user = user);
  }

  updateUser(): void {
    this.userService.updateUser(this.user)
      .subscribe(() => {
        // Handle success and navigation, if needed
      });
  }
}

Next, Create the template file user-edit.component.html to provide a form for editing the user details:

<form>
  <label>Name:</label>
  <input type="text" [(ngModel)]="user.name" name="name">
  <label>Email:</label>
  <input type="text" [(ngModel)]="user.email" name="email">
  <button (click)="updateUser()">Update User</button>
</form>

Step 11 – Update App Component & Module.ts

Open the app.component.html file, add the navigation links for user list and user create components:

<h1>Angular 16 CRUD Operations with Web rest Api Example</h1>
<nav>
  <a routerLink="/users" routerLinkActive="active">User List</a>
  <a routerLink="/users/create" routerLinkActive="active">Create User</a>
</nav>
<router-outlet></router-outlet>

Next, add the code for the app.module.ts file, where we configure and import the required modules, components, and services:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserCreateComponent } from './user-create/user-create.component';
import { UserEditComponent } from './user-edit/user-edit.component';
import { UserDetailsComponent } from './user-details/user-details.component';
import { UserService } from './user.service';

@NgModule({
  declarations: [
    AppComponent,
    UserListComponent,
    UserCreateComponent,
    UserEditComponent,
    UserDetailsComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 12 – Run Angular Application

Finally, execute the following command on cmd to start the Angular development server:

ng serve

Open your browser and navigate to http://localhost:4200. You should see your Angular 16 CRUD application in action!

Conclusion

Congratulations! You have successfully built a complete Angular 16 CRUD application that interacts with a Web REST API for user management. In this tutorial, you’ve learned how to set up an Angular 16 project, implement CRUD operations using a service, and connect to a Web REST API to perform data retrieval and manipulation.

Recommended Angular Tutorials

RELATED ARTICLES

Most Popular

Recent Comments