ANGULAR CRUD Example
ANGULAR
This chapter explains non-persistent create-read-update-delete operations to understand how services and models work in Angular.
Angular CRUD Example 01
➔ This example shows how non-persistent crud operation works in Angular using service and model.
➔ This understanding will be useful to learn how Angular will work with HTTP client API requests with persistent data sources.
Create a project by ng new crud01 command.
ng new crud01
app.module.ts file
Copy this file content to the target file.
Example
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@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?:number,name?:string,email?:string){
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() { }
getStudents(): Student[] {
return [
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"),
];
}
}
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) {
//this.stArray = this.getStudents();
this.stArray = this.stService.getStudents();
}
title = 'modelcrud01';
id: number = 0;
name: string = "";
email: string = "";
msg: string = "";
stArray: Student[];
// getStudents(): Student[] {
// return [
// 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"),
// ];
// }
addStudent() {
let found = this.stArray.find(element => element.id == this.id);
if (found == null && this.id > 0) {
this.stArray?.push(new Student(this.id, this.name, this.email));
this.msg = "Item added";
} else {
this.msg = "Item empty or already exist";
}
}
deleteStudent(id: number) {
for (let i = 0; i < this.stArray.length; i++) {
if (id == this.stArray[i].id) {
this.stArray.splice(i, 1);
this.msg = "Item Deleted";
}
}
}
updateStudent(id: number) {
for (let i = 0; i < this.stArray.length; i++) {
if (id == this.stArray[i].id) {
this.stArray[i].name = this.name;
this.stArray[i].email = this.email;
this.msg = "Item Updated";
}
}
}
}
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 mt-4">
<div class="row">
<div class="col">
<h3 class=" p-2 bg-white">{{msg}}</h3>
<form>
<div class="mb-3">
<input type="text" placeholder="Enter ID" class="form-control" id="id" name="id" [(ngModel)]="id" #id1="ngModel" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<input type="text" placeholder="Enter Name" class="form-control" id="name" name="name" [(ngModel)]="name" #name1="ngModel" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<input type="text" placeholder="Enter Email" class="form-control" id="email" name="email" [(ngModel)]="email" #email1="ngModel" aria-describedby="emailHelp">
</div>
<button type="submit" class="btn btn-primary m-3" (click)="addStudent()">Save</button>
<button type="submit" class="btn btn-primary m-3" (click)="deleteStudent(id1.value)">Delete</button>
<button type="submit" class="btn btn-primary m-3" (click)="updateStudent(id1.value)">Update</button>
</form>
</div>
<div class="col">
<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 stArray; 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>Modelcrud01</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).
program output