ANGULAR CRUD Example
ANGULAR
This chapter explains non-persistent create-read-update-delete operations to understand how services work in Angular.
Angular CRUD Example 03
➔ This example shows how non-persistent crud operation works in Angular using service.
➔ This understanding will be helpful to learn how Angular will work with HTTP API requests and data sources.
Create a project by ng new crud03 command.
ng new crud03
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
gpa?:number;
constructor(id?:number,name?:string,email?:string,gpa?:number){
this.id=id;
this.name=name;
this.email=email;
this.gpa=gpa;
}
}
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", 1),
new Student(101, "a1", "e1", 2),
new Student(102, "a2", "e2", 1.5),
new Student(103, "a3", "e3", 4),
new Student(104, "a4", "e4", 5),
];
}
}
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 = 'modelcrud03';
id: number=0;
name: string = "";
email: string = "";
gpa?: number;
msg: string = "";
stArray: Student[];
//fail="fail";
//pass="pass";
// 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.gpa));
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.stArray[i].gpa = this.gpa;
this.msg = "Item Updated";
}
}
}
getClassOf(gpa?: any) {
let ret;
if (gpa < 2) {
ret = "fail";
} else if (gpa < 4) {
ret = "better";
} else {
ret = "best";
}
return ret;
}
}
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" aria-describedby="emailHelp"
id="name" name="name" [(ngModel)]="name" #name1="ngModel"/>
</div>
<div class="mb-3">
<input type="text" placeholder="Enter Email" class="form-control" aria-describedby="emailHelp"
id="email" name="email" [(ngModel)]="email" #email1="ngModel" />
</div>
<div class="mb-3">
<input type="text" placeholder="Enter gpa" class="form-control" aria-describedby="gpaHelp"
id="gpa" name="gpa" [(ngModel)]="gpa" #gpa1="ngModel"/>
</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>
<th scope="col">GPA</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let s of stArray; let i = index">
<!-- for row style -->
<!-- <tr *ngFor="let s of stArray; let i = index;" [ngClass]="{'fail': s.gpa!<2,'best': s.gpa!>=4}"> -->
<th scope="row">{{ i + 1 }}</th>
<!-- without login apply multiple class -->
<!-- <th scope="row" [ngClass]="{'fail': false, 'better': true}">{{i+1}}</th> -->
<!-- Conditionally apply only one of two classes -->
<!-- <th scope="row" [ngClass]="s.gpa!>=4 ? 'fail' : 'better'">{{i+1}}</th> -->
<!-- <td>{{ s.id }}</td> -->
<!-- for Exact match with -->
<!-- <td [ngClass]="{'1' : 'fail', '2' : 'better', '4' : 'best'}[s.gpa!]">{{s.id}}</td> -->
<!-- for multiple condition apply -->
<td> {{ s.id }} </td>
<!-- for function call multiple condition-->
<!-- <td [ngClass]="getClassOf(s.gpa)">{{s.id}}</td> -->
<td>{{ s.name }}</td>
<td>{{ s.email }}</td>
<td [ngClass]="{ fail: s.gpa! < 2, better: s.gpa! >= 2 && s.gpa! < 4, best: s.gpa! >= 4 }" >{{ s.gpa }}</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>Modelcrud03</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