View video tutorial

ANGULAR CRUD Example

ANGULAR

This chapter explains non-persistent create-read-update-delete operations to understand how services work in Angular.

Angular CRUD Example 02


➔ This example shows how non-persistent crud operation works in Angular using service.

➔ This lesson will be useful to learn how Angular will work with HTTP client API requests with persistent data sources.

Create a project by ng new crud02 command.
ng new crud02

app.module.ts file

Copy this file content to the target file.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import{FormsModule} from '@angular/forms'

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

Copy the code and try it out practically in your learning environment.


Model student.ts file

Create a student class by ng g class student in command line.

Copy this file content to the target file.

Example
export class Student {
    id:number;
    name:string;
    email:string;
    constructor(id?:any,name?:any,email?:any){
        this.id=id;
        this.name=name;
        this.email=email;
    }
}

Copy the code and try it out practically in your learning environment.


Service student.service.ts file

Create a student service by ng g s student in command line.

Copy this file content to the target file.

Example
import { Injectable } from '@angular/core';
import { Student } from './student';

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

  constructor() { }
  students: Student[]=[
    new Student(100, "a", "e"),
    new Student(101, "a1", "e1"),
    new Student(102, "a2", "e2"),
    new Student(103, "a3", "e3"),
    new Student(104, "a4", "e4"),
  ];

  getStudents(): Student[] {
    return this.students;
  }
}

Copy the code and try it out practically in your learning environment.


app.component.ts file

Copy this file content to the target file.

Example
import { Component } from '@angular/core';
import { Student } from './student';
import { StudentService } from './student.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private stService: StudentService) { }
  title = 'modelcrud01';
  st: Student = new Student();
  students: Student[] = this.stService.getStudents();

  //error:boolean=false;
  msg: string = "";
  createStudent(i: number) {
    const found = this.students.find(element => element.id == i);
    if (found == null && i > 0) {
      this.students.push(new Student(this.st.id, this.st.name, this.st.email));
      this.students.sort((a = new Student(), b = new Student()) => a.id - b.id);
      let elementIndex = this.students.findIndex((element) => element.id == i)
      this.msg = "New Item Added at index " + (elementIndex + 1);
    } else {
      this.msg = "Item Empty or Already Exists";
    }
  }
  deleteStudent(i: number) {
    const found = this.students.find(element => element.id == i);
    let elementIndex = this.students.findIndex((element) => element.id == i)
    if (found != null) {
      this.students.splice(elementIndex, 1);
      this.msg = "Deleted {id=" + (found.id + ", name=" + found.name + "}");
    } else {
      this.msg = "Item Not Found";
    }
  }

  updateStudent(i: number, name: string, email: string) {
    //this.students = this.students.filter(data => data.id != i);
    const found = this.students.find(element => element.id == i);
    let elementIndex = this.students.findIndex((element) => element.id == i)
    if (found != null) {
      this.students.splice(elementIndex, 1, new Student(this.st.id, this.st.name, this.st.email));
      this.msg = "Item Updated for index " + (found.id);
    } else {
      this.msg = "Item Not Found";
    }
  }
}

Copy the code and try it out practically in your learning environment.


HTML app.component.html File

Copy this file content to the target file.

Example
<div class="container text-center m-3">
  <div class="row">
    <div class="col">
      <form>
        <div class="form-group">
          <input class="form-control form-control-lg m-3" type="text" id="id" name="id" #id1="ngModel"
            [(ngModel)]="st.id" aria-describedby="emailHelp" placeholder="Enter ID">
        </div>
        <div class="form-group">
          <input class="form-control form-control-lg m-3" type="text" id="name" name="name" #name1="ngModel"
            [(ngModel)]="st.name" aria-describedby="emailHelp" placeholder="Enter Name">
        </div>
        <div class="form-group">
          <input class="form-control form-control-lg m-3" type="text" id="email" name="email" #email1="ngModel"
            [(ngModel)]="st.email" aria-describedby="emailHelp" placeholder="Enter Name">
        </div>
        <button type="submit" class="btn btn-primary m-3" (click)="createStudent(id1.value)">Create</button>
        <button type="submit" class="btn btn-primary m-3" (click)="deleteStudent(id1.value)">Delete</button>
        <button type="button" class="btn btn-primary m-3"
          (click)="updateStudent(id1.value, name1.value, email1.value)">Update</button>
      </form>
    </div>
    <div class="col">
      <h2 class="m-3 p-2" style="background-color:#e0e0e0; height: 60px;">{{msg}}</h2>
      <table class="table">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">ID</th>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let s of  students; let i=index">
            <th scope="row">{{i+1}}</th>
            <td>{{s.id}}</td>
            <td>{{s.name}}</td>
            <td>{{s.email}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

Copy the code and try it out practically in your learning environment.


HTML index.html File

Copy this file content to the target file.

Example
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Modelcrud02</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js" integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

Copy the code and try it out practically in your learning environment.


Output

Run project by ng serve in command line (from inside project directory).

Angular services crud02 example

program output