Angular 15 CRUD Application Example Tutorial
In this article, we will create step by step an Angular 15 CRUD example with the rest web API from scratch(Angular 15 CRUD Application Example Tutorial). we will give a simple Angular 14 CRUD Application Example. in this example, we create an angular crud example with the rest web API.
Step 1: Create a new angular app
We will create a new angular app using the following command.
1 2 | ng new myAng11crud cd myAng11crud |
when you create your application at that time Angular CLI asks you Would you like to add Angular routing? (y/N). If you enter with y for Yes. then the angular router will be automatically configured.
Step 2: Install Bootstrap 5 in angular
After the complete created application, you can install the bootstrap using the below command.
1 | npm install bootstrap --save |
We need to add the bootstrap CSS into the angular.json file. so first we will add that path into the angular.json file.
angular.json
1 2 3 | "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", ] |
Step 3: Create Component
Now we need to create three student components for the angular crud example. So let’s run the following command to create components.
1 2 3 | ng g component student/list ng g component student/add ng g component student/edit |
src/app/student/list/list.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <div class="col-md-6 container"> <h2 style="margin: auto"> Student Details</h2> <button class="btn btn-primary" (click)="addStudent()">Add Student</button> <table class="table table-striped"> <thead> <tr> <th>Id</th> <th>FirstName</th> <th>LastName</th> <th>Address</th> <th>Action</th> </tr> </thead> <tbody> <tr *ngFor="let student of students"> <td>{{ student.id }}</td> <td>{{ student.first_name }}</td> <td>{{ student.last_name }}</td> <td>{{ student.address }}</td> <td><button class="btn btn-danger" (click)="deleteStudent(student)"> Delete</button> <button class="btn btn-success" (click)="editStudent(student)" style="margin-left: 20px;"> Edit</button></td> </tr> </tbody> </table> </div> |
src/app/student/list/list.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import { Component, OnInit } from '@angular/core'; import {Router} from "@angular/router"; import { Student } from '../student'; import {StudentService } from "../student.service"; @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.css'] }) export class ListComponent implements OnInit { students: Student[]; constructor(private router: Router, private studentService: StudentService) { } ngOnInit(): void { this.studentService.getStudents() .subscribe( data => { this.students = data.result; }); } deleteStudent(student: Student): void { this.studentService.deleteStudent(student.id) .subscribe( data => { this.students = this.students.filter(u => u !== student); }) }; editStudent(student: Student): void { window.localStorage.removeItem("editStudentId"); window.localStorage.setItem("editStudentId", student.id.toString()); this.router.navigate(['edit']); }; addStudent(): void { this.router.navigate(['add']); }; } |
src/app/student/add/add.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <div class="col-md-6 container"> <h2 class="text-center">Add Student</h2> <form [formGroup]="addForm" (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="first_name">First Name:</label> <input formControlName="first_name" placeholder="First Name" name="first_name" class="form-control" id="first_name"> </div> <div class="form-group"> <label for="lastName">Last Name:</label> <input formControlName="last_name" placeholder="Last name" name="last_name" class="form-control" id="last_name"> </div> <div class="form-group"> <label for="address">Address:</label> <input formControlName="address" placeholder="Address" name="address" class="form-control" id="address"> </div> <button class="btn btn-success">Add</button> </form> </div> |
src/app/student/add/add.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router} from "@angular/router"; import {StudentService } from "../student.service"; @Component({ selector: 'app-add', templateUrl: './add.component.html', styleUrls: ['./add.component.css'] }) export class AddComponent implements OnInit { constructor(private formBuilder: FormBuilder,private router: Router, private studentService: StudentService) { } addForm: FormGroup; ngOnInit(): void { this.addForm = this.formBuilder.group({ id: [], first_name: ['', Validators.required], last_name: ['', Validators.required], address: ['', Validators.required] }); } onSubmit() { this.studentService.createStudent(this.addForm.value) .subscribe( data => { this.router.navigate(['list']); }); } } |
src/app/student/edit/edit.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <div class="col-md-6 container"> <h2 class="text-center">Edit Student</h2> <form [formGroup]="editForm" (ngSubmit)="onSubmit()"> <div class="hidden"> <input type="text" formControlName="id" placeholder="id" name="id" class="form-control" id="id"> </div> <div class="form-group"> <label for="first_name">First Name:</label> <input formControlName="first_name" placeholder="First Name" name="first_name" class="form-control" id="first_name"> </div> <div class="form-group"> <label for="lastName">Last Name:</label> <input formControlName="last_name" placeholder="Last name" name="last_name" class="form-control" id="last_name"> </div> <div class="form-group"> <label for="address">Address:</label> <input formControlName="address" placeholder="Address" name="address" class="form-control" id="address"> </div> <button class="btn btn-success">Update</button> </form> </div> |
src/app/student/edit/edit.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | import { Component, OnInit } from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {Router} from "@angular/router"; import { Student } from '../student'; import {StudentService } from "../student.service"; import {first} from "rxjs/operators"; @Component({ selector: 'app-edit', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'] }) export class EditComponent implements OnInit { student: Student; editForm: FormGroup; constructor(private formBuilder: FormBuilder,private router: Router, private studentService: StudentService) { } ngOnInit() { let studentId = window.localStorage.getItem("editStudentId"); if(!studentId) { alert("Invalid action.") this.router.navigate(['list']); return; } this.editForm = this.formBuilder.group({ id: [''], first_name: ['', Validators.required], last_name: ['', Validators.required], address: ['', Validators.required] }); this.studentService.getStudentById(+studentId) .subscribe( data => { this.editForm.setValue(data); }); } onSubmit() { this.studentService.updateStudent(this.editForm.value) .pipe(first()) .subscribe( data => { if(data.status === 200) { alert('Student updated successfully.'); this.router.navigate(['list']); }else { alert('somthing went to wrong!'); } }, error => { alert(error); }); } } |
Step 4: Create an Angular app Interface
In this step, we need to create the Interface and it handles asynchronous operations. so you can create using the following command.
1 | ng generate interface student/student |
src/app/student/student.ts
1 2 3 4 5 6 | export interface Student { id: number; first_name: string; last_name: string; address: string; } |
Step 5: creating angular app services
now, we will create the student app services using the following command. it is used to get the data from the backend by calling rest API. it is used to get the data from the backend by calling rest API. so we need to rest API and you can use any type of created rest API.
1 | ng generate service student/student |
src/app/student/student.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import { Injectable } from '@angular/core'; import { HttpClient,HttpHeaders } from '@angular/common/http'; import { Student } from './student'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class StudentService { constructor(private httpClient: HttpClient) { } baseUrl: string = 'http://localhost/codeigniter4_rest_api/student'; httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } getStudents() : Observable<Student> { return this.httpClient.get<Student>(this.baseUrl); } getStudentById(id: number): Observable<Student> { console.log(id); return this.httpClient.get<Student>(this.baseUrl+'/'+ id); } createStudent(student: Student): Observable<Student> { console.log('create'); return this.httpClient.post<Student>(this.baseUrl, student); } updateStudent(student: Student): Observable<Student> { return this.httpClient.put<Student>(this.baseUrl+'/'+ student.id, student); } deleteStudent(id: number): Observable<Student> { return this.httpClient.delete<Student>(this.baseUrl+'/'+ id); } } |
Step 6: Angular App Routing Module
In this step, we will import each and every component and configure the route path in this file. so you can see the below example.
src/app/app-routing.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {AddComponent} from "./student/add/add.component"; import {ListComponent} from "./student/list/list.component"; import {EditComponent} from "./student/edit/edit.component"; const routes: Routes = [ { path: 'add', component: AddComponent }, { path: 'list', component: ListComponent }, { path: 'edit', component: EditComponent }, {path : '', component : ListComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } |
Step 7: Angular 15 App Module
finally, we will import the module in this file. so you can see the below example.
src/app/app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import { FormsModule, ReactiveFormsModule} from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ListComponent } from './student/list/list.component'; import { AddComponent } from './student/add/add.component'; import { EditComponent } from './student/edit/edit.component'; @NgModule({ declarations: [ AppComponent, ListComponent, AddComponent, EditComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
Step 8: Run Angular Application
Now we will run our Angular application using the below command.
1 | ng serve |